In this article, we will see how to display the content dynamically based on the selected value in reactjs

Using state

By utilizing the component state, we can efficiently update and render content based on user interactions.

Let’s get started by initializing a state variable that will hold the selected value. For example:

import React, { useState } from 'react';

const ContentDisplay = () => {
  const [selectedValue, setSelectedValue] = useState('');

  // Rest of the component...

Next, we need to create an event handler that updates the selected value whenever it changes. This can be done by attaching an onChange event to the element such as a dropdown or radio button. See the following example for more information.

const handleValueChange = (event) => {

After which, we need to render the content based on the value. Within the component’s render function, we need to conditionally render the content based on the selected value. Use conditional statements such as if or switch case to determine which content to display.

return (
    <select value={selectedValue} onChange={handleValueChange}>
      <option value="option1">Option 1</option>
      <option value="option2">Option 2</option>
      <option value="option3">Option 3</option>

    {selectedValue === 'option1' && <div>Content for Option 1</div>}
    {selectedValue === 'option2' && <div>Content for Option 2</div>}
    {selectedValue === 'option3' && <div>Content for Option 3</div>}

In the above example, the content will be displayed based on the option selected in the dropdown.

Categorized in:

Tagged in: