Can I change a component's attribute values using a conditional statement in the render function?

Question

Can I change a component’s attribute values using a conditional statement in the render function?

Answer

Absolutely! We can change attribute values of components/elements based on a condition - this functionality is useful in many cases, including changing a className based on a condition.

For example, say we want to render a button and want it to have a different background color based on a condition - to add this functionality to our component we need to set the className attribute value based on said condition like this:

import React from 'react';
import ReactDOM from 'react-dom';

class MyButton extends React.Component {
  render() {
    let colorChoice = 'blue';
    let buttonClassName;

    if(colorChoice === 'red'){
      buttonClassName = 'red-button';
    } else {
      buttonClassName = 'blue-button';
    }

    return (
    <button className={buttonClassName}>Here's a button!</button> // the className attribute can be set by injecting JS into our component, in this example className is set based on a condition
    )
  }
};

ReactDOM.render(
  <MyButton />,
  document.getElementById('app')
);

Then in our CSS we would have something like this:

.red-button {
  background-color: red;
}

.blue-button {
  background-color: blue
}
9 Likes

Wait a second?! Does this example mean avoiding writing those particular attributes out in CSS? Or would you still have to define them in the separate CSS document as usual?

1 Like

“Then in our CSS we would have something like this” - this sentence probably seems a bit misleading.
I think we need to have the “background-color” pre-defined for ‘red-button’ and ‘blue-button’ classes in CSS for the attributes to work for the button element that we are rendering.

According to this page, you can also use an inline stylesheet if you would rather not use an external one, and just style the button directly.

example:

class MyButton extends React.Component {
  render() {
    let colorChoice = 'blue';
    let buttonColor;

    if(colorChoice === 'red'){
      buttonColor = {backgroundColor: "red"};
    } else {
      buttonColor = {backgroundColor: "blue"};
    }

    return (
    <button style={buttonColor}>Here's a button!</button>
    );
  }
};
2 Likes

Can’t we use && operator or ternary operations inside JSX