React: How to display other components when clicked

Toggle the visibility of a component by telling React to show another component when you click on something

In many cases, when you click a button or link, you want to display completely different components on the screen.

For example, consider the navigation structure.

How can you do this?

In this example, I manage the state concentrated in the App component.

import React from 'react'

const AddTripButton = (props) => { return <button onClick={props.addTrip}>Add a trip</button> }

export default AddTripButton

Then, in the App component, by assigning the addTrip event totriggerAddTripStatemethod:

<AddTripButton addTrip={this.triggerAddTripState} />

To use React hooks, first import useState:

import { useState } from 'react'

Then declare a "state" variable:

const [state, setState] = useState('start')

In JSX, you can show and hide different components based on the following status values:

function App() {
  const [state, setState] = useState('start')

triggerAddTripState = () => { setState(‘add-trip’) }

return ( <div> {state === ‘start’ && ( <AddTripButton addTrip={this.triggerAddTripState} /> )}

  {<span style="color:#a6e22e">state</span> <span style="color:#f92672">===</span> <span style="color:#e6db74">'add-trip'</span> <span style="color:#f92672">&amp;&amp;</span> <span style="color:#f92672">&lt;</span><span style="color:#a6e22e">AnotherComponent</span> <span style="color:#f92672">/&gt;</span>}
<span style="color:#f92672">&lt;</span><span style="color:#960050;background-color:#1e0010">/div&gt;</span>

) }

With class-based components,triggerAddTripStateYou edit the status of the component:

class App extends Component {
  constructor(props) {
    super(props)
    this.state = { isEmptyState: true }
  }

triggerAddTripState = () => { this.setState({ …this.state, isEmptyState: false, isAddTripState: true }) } }

See, here I create a default state, which containsisEmptyState: true. when. . . whentriggerAddTripStateRun the method, edit the state so that the property is set to false, and then create a new oneisAddTripStateThe property is set to true.

Now, in JSX, we can use the following 2 state attributes to show and hide certain parts of the component through the following syntax:

render() {
  return (
    <div>
      {this.state.isEmptyState && <AddTripButton addTrip={this.triggerAddTripState} />}
  {<span style="color:#66d9ef">this</span>.<span style="color:#a6e22e">state</span>.<span style="color:#a6e22e">isAddTripState</span> <span style="color:#f92672">&amp;&amp;</span> <span style="color:#f92672">&lt;</span><span style="color:#a6e22e">AnotherComponent</span> <span style="color:#f92672">/&gt;</span>}
<span style="color:#f92672">&lt;</span><span style="color:#960050;background-color:#1e0010">/div&gt;</span>

) }

Download mine for freeResponse Handbook


More response tutorials: