From React Class component to Functional component with hooks

Change inline CSS Conditionally Based on Component State

In the previous article, we learnt how to Render conditionally React child components from props. In this nineteenth episode, we will review out to insert inline CSS into JSX, first. Then we will discover how to change inline CSS conditionally based on component state.

The example used to illustrate this article is a free Code Camp challenge that we will code in both class and functional components. But, first of all, let’s review how to use CSS in JSX.

Summary

Review – JSX and CSS

You can use stylesheet and inline CSS with JSX.

JSX and Stylesheet

If styles are imported from a stylesheet, it isn’t much different as working with HTML at all.

  1. Apply a class to the JSX element using the className attribute (instead of class).
  2. Apply styles to the class in the stylesheet.
HTML
<div class=”brand”>Mellow Yellow</div>
JSX
<div className=”brand”>Mellow Yellow</div>

Another option is to apply inline styles, which are very common in ReactJS development.

JSX and inline CSS

JSX and style attribute

Applying inline styles to JSX elements is similar to how to do it in HTML, but with a few JSX differences.

  • JSX elements use the style attribute,
  • but because of the way JSX is transpiled, the value cannot be set to a string but a JavaScript object. This object is inserted between curly braces.
  • As React does not accept kebab-case keys in the style object, the property must be camelCased. Look at the font-size property which becames fontSize). However, React will apply the correct property name in the HTML.
  • All property value length units (like height, width, and fontSize) are assumed to be in px unless otherwise specified. To use em, for example, the value and the units must be wrapped in quotes, like {fontSize: “4em”}. Other than the length values that default to px, all other property values should be wrapped in quotes.
HTML
<div style=”color: yellow; font-size: 16px”>Mellow Yellow</div>
JSX
<div style={{color: “yellow”, fontSize: 16}}>Mellow Yellow</div>

Need to train? Try to pass the React Introducing Inline Style free Code camp challenge.

JSX and CSS in a constant

When there is a large set of styles, it is possible to assign a style object to a constant to keep the code organized.

  1. Declare the styles constant as a global variable at the top of the file.
  2. Initialize styles constant and assign an object with style properties and their values to it.
    • The properties are in cameCase.
    • The value containing units must be wrapped in quotes.
    • The properties are separated by “,” instead of “;” as in CSS language.
  3. Set the style attribute equals the constant (between curly braces).
class Colorful extends React.Component {
  render() {
    const styles = {color: “purple”, fontSize: 40, border: “2px solid purple”}
    return (
      <div style={styles}>Style Me!</div>
    );
  }
};

Need to train? Try to pass the Add Inline styles in React free Code Camp challenge.

Now that we have reviewed the CSS in JSX characteristics, let’s try to render CSS conditionally based on the state of a React component.

Render CSS conditionally based on the state of a React Component

From now on, we are able to combine conditional rendering and inline CSS. We can render CSS conditionally based on the state of a React component.

  1. Check for a condition.
  2. If that condition is met, modify the styles object that’s assigned to the JSX elements in the render method.#change-inline-css-conditionally-based-on-state-in-a-class-component

Example: Render a Controlled Input with CSS conditionally based on its state

More about the Example App

  • Aspect: The App has a simple controlled input component with a styled border 1px solid black.
  • What happens when the the user types more than 15 characters of text in the input box?  This border must be styled red.
  • How to do that? Add a condition to check for this and, if the condition is valid, set the input border style to 3px solid red.
  • How to control? Try it out by entering text in the input.

This example is based on a free Code Camp challenge. Why not to try to pass it? We will code it in a class component and then in a functional component.

Change inline CSS Conditionally Based on State in a class component

Condition the React class component rendering with CSS step by step

  1. React has been installed.
  2. Create the HTML element and its id to attach the React App.
  3. Create the GateKeeper class component.
  4. Declare the input state property and initialize it with an empty string.
  5. In the return statement of the render method,
    • create the h3 element whose text is Don’t type too much!
    • create the input element assign it: a value attribute and pass it the state input property, a style attribute and pass it the inputStyle variable, an onClick event and pass it the handleChange method as event handler method.
  6. Above the render method, declare the handleChange method and pass it the event. Set the state applying it the event.target.value. Remark: do not forget to bind the method!
  7. In the render method, above the return statement, declare the inputStyle variable with let. Pass it the border CSS property in an object. The border value must be 1px solid black. That will be the initial aspect of the Input.
  8. Below the variable, indicate a condition in an if statement. The condition is that the input state length must be more than 15. In that case the inputStyle border property must be 3px solid red.  there are two solutions to code this part. Refer to the below full code.

The final code in a class component

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’
    };
    if (this.state.input.length > 15) {
      inputStyle.border = ‘3px solid red’
    }
    //second solution
    /*
    if (this.state.input.length > 15) {
      inputStyle = {
        border: ‘3px solid red’
      }
    }
    */
    return (
      <div>
        <h3>Don’t Type Too Much:</h3>
        <input
          type=”text”
          style={inputStyle}
          value={this.state.input}
          onChange={this.handleChange} />
      </div>
    );
  }
};
ReactDOM.render(<GateKeeper />, document.getElementById(‘conditional-rendering’));

Play with the pen

See the Pen
React tricks: Change inline CSS conditionnaly based on class component state 2
by Coding-Tricks (@coding-tricks)
on CodePen.

Change inline CSS Conditionally Based on State in a functional component

Condition the React functional component rendering with CSS step by step

  1. React has been installed.
  2. Create the HTML element and its id to attach the React App.
  3. Create the GateKeeper functional component.
  4. Declare the input state property and its updating function. Initialize it with an empty string.
  5. In the return statement,
    • create the h3 element whose text is Don’t type too much!
    • create the input element assign it: a value attribute and pass it the state input property, a style attribute and pass it the inputStyle variable, an onClick event and pass it the handleChange function as event handler function.
  6. Above the return, declare the handleChange function and pass it the event. Set the state applying it the event.target.value.
  7. Above the return, declare the inputStyle variable with let. Pass it the border CSS property in an object. The border value must be 1px solid black. That will be the initial aspect of the Input.
  8. Below the variable, indicate a condition in an if statement. The condition is that the input state length must be more than 15. In that case the inputStyle border property must be 3px solid red.  there are two solutions to code this part. Refer to the below full code.

The final code in a functional component

import { useState } from ‘react’;
const GateKeeper = () => {
  const [input, setInput] = useState(“”);
  const handleChange = (event) => {
    setInput(event.target.value);
  };
  let inputStyle = {border: “1px solid black”};
  if (input.length > 15) {
    inputStyle.border = “3px solid red”;
  }
  /*
  if (input.length > 15) {
    inputStyle = {border: “3px solid red”};
  }
  */
  return (
    <div>
      <h3>Don’t Type Too Much!</h3>
      <input
        type=”text”
        style={inputStyle}
        value={input}
        onChange={handleChange}
      />
    </div>
  );
};
ReactDOM.render(<GateKeeper />, document.getElementById(‘conditional-rendering’));

Play with the pen

See the Pen
React tricks: Change inline CSS conditionnally based on a class component state
by Coding-Tricks (@coding-tricks)
on CodePen.

In conclusion

In this episode we have reviewed the CSS in JSX and discovered how to render CSS conditionally based on a component state in both class and functional components.

In the next episode, will learn what is the useRef hook and when to use it.

comment

There is no comments. Leave the first one!

Leave a Reply

Your email address will not be published. Required fields are marked *

Haut de page