We can conditionally add attributes to React components with the following approaches:
Approach 1:
Evidently, with some attributes, React is smart enough to omit the attribute if the value you pass to it is not truthy. For example:
state= { disabled: false, required: true } return ( <input type="text" disabled={disabled} required={required} /> );
Above Syntax will result in the following output:
<input type="text" required>
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Approach 2: We can use the below syntax:
state { condition: true } return ( <Button {...(condition ? {className: 'btn btn-primary'} : {})} /> );
Depending on the value of condition either the {className: ‘btn btn-primary’} or {} will be returned. The Spread Operator will then spread the returned object properties to the Button component. In the falsy case, because the returned object has no properties, nothing will be passed to the component.
Approach 1:
Javascript
import React, { Component } from "react" ; class App extends Component { state = { disabled: true , text: "Make it Unable" } updateState = () => { let text = ! this .state.disabled ? "Make it Unable" : "Make it Disable" ; this .setState({ disabled: ! this .state.disabled, text: text }) } render() { return ( <div> <input type= "text" disabled={ this .state.disabled} /> <button onClick={ this .updateState}> { this .state.text} </button> </div> ); } } export default App; |
Output:
Approach 2:
Javascript
import React, { Component } from "react" ; class App extends Component { state = { condition: true } updateState = () => { this .setState({ condition: ! this .state.condition }) } render() { return ( <div> <button {...( this .state.condition ? { className: 'btn btn-primary' } : {})} onClick={ this .updateState}> click </button> </div> ); } } export default App; |
Output: