Skip to content

React: How to show a different component on click

New Course Coming Soon:

Get Really Good at Git

Toggle the visibility of components by telling React to display another component when you click something

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')

  return (
      {state === 'start' && (
        <AddTripButton addTrip={() => setState('add-trip') } />

      {state === 'add-trip' && <AnotherComponent />}
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my React Beginner's Handbook
→ Read my full React Tutorial on The Valley of Code

Here is how can I help you: