React: How to Toggle Display of Different Components on Click
In React, it is common to want to display a different component when a button or link is clicked. This can be useful in scenarios like navigation menus, where you want to show different sections of your application based on user interactions. In this blog, we will explore how to achieve this functionality.
To begin with, let’s create a simple button component called AddTripButton
, which will trigger the display of a different component when clicked:
1 | import React from 'react'; |
Next, in our main App
component, we will manage the state and handle the click event. The state will determine which component should be displayed:
1 | import React, { useState } from 'react'; |
In the above example, we import useState
from the react
library to manage the state hook. We declare a state
variable and a corresponding setState
function to update it. Initially, the state
is set to 'start'
.
In the App
component’s JSX, we conditionally render the AddTripButton
component based on the state
value. When the button is clicked, it triggers the triggerAddTripState
function, which updates the state
to 'add-trip'
. This, in turn, displays the AnotherComponent
.
By following this approach, you can easily toggle between different components based on user interactions.
Tags: React, component toggle, event handling, state management