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:
- Create a new file named index.html
- 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>
- Save the file
Then, create a new file containing the logic of the React application and your component:
- Create a new file named conditions.js
- Import the React and ReactDOM libraries:
import * as React from 'react' import * as ReactDOM from 'react-dom'
- 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] )
- 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> ) } }
- Render the application:
ReactDOM.render( <App />, document.querySelector('[role="main"]'), )
- Save the file.