Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!


In many scenarios you want to display a completely different component inside a screen, when a button or link is clicked.

Think about a navigation structure, for example.

How can you do so?

In this example I’m managing the state centralized 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, handle the addTrip event by assigning it the triggerAddTripState method:

<AddTripButton addTrip={this.triggerAddTripState} />

With React hooks, first import useState:

import { useState } from 'react'

then declare a “state” variable:

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

In the JSX you show and hide different components based on this state value:

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

  triggerAddTripState = () => {
    setState('add-trip')
  }

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

      {state === 'add-trip' && <AnotherComponent />}
    </div>
  )
}

With class-based components, in triggerAddTripState you edit the state 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 contains isEmptyState: true. When the triggerAddTripState method is run, the state is edited so that property is set to false, and a new isAddTripState property is set to true.

Now in the JSX we can use those 2 state properties to show and hide parts of the component by using this syntax:

render() {
  return (
    <div>
      {this.state.isEmptyState && <AddTripButton addTrip={this.triggerAddTripState} />}

      {this.state.isAddTripState && <AnotherComponent />}
    </div>
  )
}

Download my free React Handbook



The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!

More react tutorials: