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