How to do it...

Write a React component that will decide which of two different React elements, given as children to your component, will be displayed according to a condition passed as a property. If the condition is true, then the first child is displayed. Otherwise, the second child should be displayed.

First, create an index.html file where the React application will be rendered:

  1. Create a new file named index.html
  2. Add the following HTML code:
      <!DOCTYPE html> 
      <html lang="en"> 
      <head> 
          <meta charset="UTF-8"> 
          <title>Conditional Rendering</title> 
      </head> 
      <body> 
          <div role="main"></div> 
          <script src="./conditions.js"></script> 
      </body> 
      </html> 
  1. Save the file

Then, create a new file containing the logic of the React application and your component:

  1. Create a new file named conditions.js
  2. Import the React and ReactDOM libraries:
      import * as React from 'react' 
      import * as ReactDOM from 'react-dom' 
  1. Define a functional component named Toggle that will receive a condition property that will be evaluated to define which React element to render. It expects to receive two React elements as children:
      const Toggle = ({ condition, children }) => ( 
          condition 
              ? children[0] 
              : children[1] 
      ) 
  1. Define a class component named App that will render a React element based on the defined condition. When the button is clicked, it will toggle the color state:
      class App extends React.Component { 
          constructor(props) { 
              super(props) 
              this.state = { 
                  color: 'blue', 
              } 
              this.onClick = this.onClick.bind(this) 
          } 
          onClick() { 
              this.setState(({ color }) => ({ 
                  color: (color === 'blue') ? 'lime' : 'blue' 
              })) 
          } 
          render() { 
              const { color } = this.state 
              return ( 
                  <React.Fragment> 
                      <Toggle condition={color === 'blue'}> 
                          <p style={{ color }}>Blue!</p> 
                          <p style={{ color }}>Lime!</p> 
                      </Toggle> 
                      <button onClick={this.onClick}> 
                          Toggle Colors 
                      </button> 
                  </React.Fragment> 
              ) 
          } 
      } 
  1. Render the application:
      ReactDOM.render( 
          <App />, 
          document.querySelector('[role="main"]'), 
      ) 
  1. Save the file.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.213.27