DEV Community

Randy Rivera
Randy Rivera

Posted on

React: Change Inline CSS Conditionally Based on Component State

  • In this post, FreeCodeCamp will talk about combining applications of conditional rendering and the use of inline styles. You can also render CSS conditionally based on the state of a React component. To do this, you check for a condition, and if that condition is met, you modify the styles object that's assigned to the JSX elements in the render method.
  • Code:
class GateKeeper extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: ''
    };
    this.handleChange = this.handleChange.bind(this);
  }
  handleChange(event) {
    this.setState({ input: event.target.value })
  }
  render() {
    let inputStyle = {
      border: '1px solid black'
    };
    // Change code below this line

    // Change code above this line
    return (
      <div>
        <h3>Don't Type Too Much:</h3>
        <input
          type="text"
          style={inputStyle}
          value={this.state.input}
          onChange={this.handleChange} />
      </div>
    );
  }
};
Enter fullscreen mode Exit fullscreen mode
  • Here we have a simple controlled input component with a styled border. You want to style this border red if the user types more than 15 characters of text in the input box.

*Answer:

  render() {
    let inputStyle = {
      border: '1px solid black'
    };
    if (this.state.input.length > 15) {
       inputStyle.border = '3px solid red'
    }
Enter fullscreen mode Exit fullscreen mode

Notes:

  • When you set a style object based on a condition, you describe how the UI should look as a function of the application's state. There is a clear flow of information that only moves in one direction. This is the preferred method when writing applications with React.

Larson, Q., 2019. Frontend Development Libraries. [online] Freecodecamp.org. Available at: https://www.freecodecamp.org/learn/front-end-development-libraries/react

Discussion (0)