React inline conditional component attribute

react: render conditionally from props
react render component onclick
react conditional render multiple elements
conditional rendering react
react conditional attribute
react hooks conditional rendering
react: use a ternary expression for conditional rendering
conditional rendering react functional component

I've been searching everywhere and can't find an answer to my question. So I want a conditional attribute which is only displayed on certain conditions, example:

<Button {this.state.view === 'default' && 'active'}></Button>

As you can see I only want to indicate the button active if the this.state.view is equal to default. However, I get Unexpected token, error...

But when I try to put an attribute before it, for example:

<Button isActive={this.state.view === 'default' && 'active'}></Button>

It passes the syntax error and displays fine but this is not what I wanted to achieve.

How can I fix this? And what could be the reason behind it not passing?

UPDATE

So I just found out that in react-bootstrap the property active is a shorthand of active=true so I solved it using

<Button active={this.state.view === 'default'}></Button>

So In case, someone encounters this problem I'm leaving it here. However, I still want to know why the conditional attribute is failing without enclosing it inside a prop-like syntax, example:

This:

active={this.state.view === 'default'}

Versus

{this.state.view === 'default' && 'active'}

First of all, JSX is just a syntactic sugar for React.createElement. So, it may look like, but, in reality, you don't specify html attributes: in fact, you are always passing props.

For instance, the JSX code <input type="button" value="My button" /> is transpiled into React.createElement('input',{type:'button',value:'My Button'}). And, when necessary, React engine renders this React Element to the DOM as a HTML element.

That said, we have that JSX transpiles a prop without a value as true (check docs). For instance: <Button active></Button> is transpiled to React.createElement(Button, { active: true });.

But, we know that HTML5 specification does not accept attribute=true (as pointed here). For instance: <button disabled=true></button> is invalid. The correct is <button disabled></button>.

So, to render the HTML element to the DOM, React considers only props that are valid attributes (if not, the attribute is not rendered). Check all supported html attributes. And, then, finally, if it's a boolean attribute, it removes the true/false value, rendering it properly.

For instance: <button active={true}></button> is transpiled to React.createElement("button", { active: true }); and then React renders to the DOM <button></button>, because there is no active attribute in HTML specification for the <button/> tag (is not in the supported attributes list).

But <button disabled={true}></button> is transpiled to React.createElement("button", { disabled: true }); and React renders to the DOM <button disabled></button>.

I just said that to clarify your case.

You're trying to pass an active prop to the Button component (first letter uppercase means that's a React component: there is a React Component called Button handled somewhere in your code).

That means:

<Button active></Button> is transpiled to React.createElement(Button, { active: true });

and

<Button active={true}></Button> is transpiled to React.createElement(Button, { active: true });

The same thing!

So, if you want to do a conditional prop, you can simply do something like that:

<Button active={this.state.view === 'default'}></Button>

You have a condition inside brackets. Means that, if your this.state.view is equal to default (true), active prop will be passwed down to the component with the true value. If not equal, with the false value.

Button Component, then, must someway handle this active prop. It can render the button element and, for instance, change it's style, pass the disabled prop... I created a fiddle to demonstrate this: https://jsfiddle.net/mrlew/5rsx40gu/

Conditional Rendering – React, Therefore, if the condition is true , the element right after && will appear in the output. If it is false , React will ignore and skip it. Inline If-Else with Conditional  Conditional Rendering In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application. Conditional rendering in React works the same way conditions work in JavaScript.

Actually, I guess it is a duplicated question that I answered it in this link sometimes ago. for this specific post, there is no need condition prop for a boolean value, because it works well like below:

const { booleanValue } = this.props;
return (
    <input checked={booleanValue} />
);

Or make your own boolean value:

const booleanValue = someThing === someOtherThing;
return (
    <input checked={booleanValue} />
);

Both of them work well, because when the booleanValue is false, react doesn't see the active prop, hence it does not exist, unless you pass checked prop to a specific component that the component will receive false checked prop from this.props.

But, if you wanna a have a prop on your specific component with a condition and if the condition returns false you don't want it there are two ways, I like second:

First:

<Component someProp={condition ? yourValue : undefined} />

Second:

<Component {...(condition && { someProp: yourValue })} />

Conditionally adding props to React Components, In React, you can conditionally add attributes to React components. You can do this by using inline conditionals inside the attribute, if statements, or even a  React - Change Inline CSS Conditionally Based on Component State If you're having trouble with freeCodeCamp's Change Inline CSS Conditionally Based on Component State challenge, you're probably not alone. In this challenge, you need to add code to change some inline CSS conditionally based on the state of a React component.

In JSX, component properties (or props) compile to a plain JavaScript object. Prop names are used as the keys of the object, and prop values are stored under those keys. The first example from the JSX docs does a great good job demonstrating this. In your case {view === 'default' && true} is a raw value without an associated prop name. Without a prop name to use as a key (specified by the syntax name=), JSX has nowhere to put that value in the final props object.

However, JSX will accept props via your original syntax if the expression inside the curly braces evaluates to an object. For example, you could do {{ active: view === "default" }}. In this case JSX can get both the key and value that it needs from the provided object, so no active= is necessary.

8 conditional rendering methods in React, If/else; Prevent rendering with null; Element variables; Ternary operator Now, for the render method, check the mode state property to either  Conditionally changing styled components based on props. Just like with normal CSS in react, we can adjust the style based on JavaScript logic. Because styled components are just components, the way to feed them values is via props. We can access the props of the styled component like this:

React Conditional Rendering, Learn about ternary operators, switch case, and if else statements in JSX to In a conditional render, a React component decides based on one or However, if it wouldn't depend on the text property, you could use an enum  In this post, I will show several ways to use conditionals while rendering html or component in jsx. Consider we have a component, and based on a boolean flag we want to show or hide a paragraph <p> Below is a small component which receives props having book name and author name. Lets not concentrate on how the whole app works.

If-Else in JSX, If a ternary expression isn't robust enough, you can use if statements outside of your JSX to determine which components should be used: var loginButton; if  If the information from the props is null or undefined, the React component returns null in the conditional rendering. There, a React component that returns null instead of JSX will render nothing. In this example, we have done the conditional rendering based on props, but the conditional rendering could be based on state and hooks too.

React conditionally add attributes, In React it's very good practice to use "Ternary operator" which can help you conditionally render Components. Therefore, the code you have is equivalent to:​  In this React 16+ tutorial, we’ll get to know How to dynamically manage the className property on components by adding conditional expressions in the function and class components using the classnames package. Sometimes we may face a situation where even classes on the components need dynamic implementations.

Comments
  • I posted an answer. But I think I misundertood. What do you mean by indicate the button active? you mean styling? or an custom active attribute (AFAIK there is no native html active atrribute, but disabled)?
  • @mrlew an active attribute. I actually solved it and posted an update but I'm still wondering the difference between the 2 syntax. It would have been easier just to print active inside the component versus active=true
  • I got your point. Just replaced my answer.
  • Thanks for your time and effort
  • You're welcome my dear friend @AhmedMahmoud.