Saturday, December 28, 2024
Google search engine
HomeLanguagesHow to conditionally add attributes to React components?

How to conditionally add attributes to React components?

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: 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments