From React Class component to Functional component with hooks

Render conditionally from props

In the previous article, we learnt how to render conditionally with the if/else statements, the && logical operator and the ternary operator. In this eighteenth episode, we will learn how to use given props to automatically and conditionally render code!

Summary

This article is based on a free Code Camp challenge in React class components. Don’t worry! We will Render conditionally from props in functional components too!

Information about the App we are going to code

In this article we will create a simple game where the user presses a button to see if he/she wins or loses.

Topics

In this App, we’ll:

  • set up a child component to make rendering decisions based on props;
  • use the ternary operator;
  • use Math.random() in a simple expression to randomly returns a different value every time it is run.

Structure of the App

This App is made of two components:

  • a parent component called GameOfChance which contains:
    • a button whose text is Play again,
    • the child component Results,
    • a paragraph whose content is the number of times the user has played;
  • a child called Results which renders whether the user wins or lose in a heading.

The random expression

The expression returns a value between 0 (inclusive) and 1 (exclusive) each time it is called. So for 50/50 odds, use Math.random() >= .5 in the expression. Statistically speaking, this expression will return true 50% of the time, and false the other 50%.

As returning a boolean, the expression can be used as a prop value. So, the render of the child component can be conditioned to the given prop!

Render conditionally from props in class components

Code the App step by step using class components

  1. Create the HTML element and assign it the id “conditional-rendering”. Then attach the App to it.
  2. Declare the parent component GameOfchance in a class component.
  3. Initialize the counter state property with 1.
  4. In the return statement of the render method,
    • create a button element whose text is “Play Again”, assign it an onClick event and pass it the handleClick method as event handler method;
    • nest the child component Results;
    • create a paragraph element which displays “Turn: ” and the number of times the user has played via the counter state.
  5. Above the render method, create the handleClick() event handler method which sets the counter state property by adding one every time the button is clicked so the user knows how many times he/she has played. This also serves to let the user know the component has actually updated in case they win or lose twice in a row. Remark: Do not forget to bind the method!
  6. In the render method, above the return statement, use advanced JavaScript by declaring a constant. Name it expression, and give use the Math.random method to obtain true 50% of the time and false 50% of the time, as a result. Refer to above section. Now we have an expression that we can use to make a randomized decision in the code.
  7. Assign a prop called fiftyFifty to the Results nested child component. Pass it the expression as value.
  8. Create the Results component, write a ternary expression to render the h2 element with the text “You Win!” or “You Lose!” based on the fiftyFifty prop that’s being passed in from GameOfChance.
  9. Test the App below in the pen!

Find the full code below.

The final code to render conditionally from props in class components

class Results extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return <h2>{ this.props.fiftyFifty ? ‘You Win!’ : ‘You Lose!’}</h2>;
  }
}
class GameOfChance extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 1
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState(state => ({
      counter: this.state.counter + 1
      })
    );
  }
  render() {
    const expression = Math.random() >= .5 ? true : false;
    return (
        <div>
          <button onClick={this.handleClick}>Play Again</button>
          <Results fiftyFifty={expression} />
          <p>{‘Turn: ‘ + this.state.counter}</p>
        </div>
      );
    }
}
ReactDOM.render(<GameOfChance />, document.getElementById(‘conditional-rendering’));

Play with the pen

See the Pen
React tricks: Conditional rendering from props on a class component
by Coding-Tricks (@coding-tricks)
on CodePen.

Render conditionally from props in functional components

Code the App step by step using functional components

  1. Create the HTML element and assign it the id “conditional-rendering”. Then attach the App to it.
  2. Import the useState hook.
  3. Declare the functional parent component GameOfchance  .
  4. Declare the counter state property and its updating function setCounter. Initialize the counter state property with 1.
  5. In the return statement of the component function ,
    • create a button element whose text is “Play Again”, assign it an onClick event and pass it the handleClick function as event handler function;
    • nest the child component Results;
    • create a paragraph element which displays “Turn: ” and the number of times the user has played via the counter state.
  6. Declare the handleClick() event handler function which updates the counter state property by adding one every time the button is clicked so the user knows how many times he/she has played. This also serves to let the user know the component has actually updated in case he/she wins or loses twice in a row.
  7. Declare a constant. Name it expression, and use the Math.random method to obtain true 50% of the time and false 50% of the time, as a condition. Refer to above section. Now we have an expression that we can use to make a randomized decision in the code.
  8. Assign a prop called fiftyFifty to the Results nested child component. Pass it the expression as value.
  9. Create the Results child component, write a ternary expression to render the h2 element with the text “You Win!” or “You Lose!” based on the fiftyFifty prop that’s being passed in from GameOfChance.
  10. Test the App below in the pen!

Find the full code below.

The final code to render conditionally from props in functional components

import { useState } from ‘react’;
const Results = ({fiftyFifty}) => {
  return (
    <h1>{fiftyFifty ? “You win!” : “You Lose!”}</h1>
  );
};
const Game = () => {
  const [counter, setCounter] = useState(1)
  const handleClick = () => {
    setCounter(counter + 1);
  };
  const expression = Math.random() >=.5 ? true : false;
  return (
    <div>
      <button onClick={handleClick}>Play Again</button>
      <Results fiftyFifty={expression} />
      <p>Turn:  {counter}</p>
    </div>
  );
};
ReactDOM.render(<Game />, document.getElementById(‘conditional-rendering’));

Play with the pen

See the Pen
React tricks: conditional rendering from props on a functional component
by Coding-Tricks (@coding-tricks)
on CodePen.

In conclusion

Done! In this episode we have learnt how to render conditionally from props. Once again we have managed to code the same App in both class and functional components!

Possible improvements: We could think about not to display a result before the first click, the text of the button that could be “Play” at the first rendering and “Play again” after the first click…

In the next episode, we will change inline CSS conditionally based on component state. Interesting, isn’t 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