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:
import React from 'react';
const AddTripButton = (props) => {
return <button onClick={props.addTrip}>Add a trip</button>;
};
export default AddTripButton;
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:
import React, { useState } from 'react';
import AddTripButton from './AddTripButton';
import AnotherComponent from './AnotherComponent';
function App() {
const [state, setState] = useState('start');
const triggerAddTripState = () => {
setState('add-trip');
};
return (
<div>
{state === 'start' && <AddTripButton addTrip={triggerAddTripState} />}
{state === 'add-trip' && <AnotherComponent />}
</div>
);
}
export default App;
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