fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← React

React / 3 MIN READ

Buttons from JSON

Creating Buttons from JSON file

From the original Fervor library. Examples may use older package versions.

Dynamic Webpage with React: Creating Buttons and Output from JSON

Introduction

Welcome to FrOnt3nd Tutorials! In this tutorial, we’ll explore how to create a dynamic webpage using React, where we’ll generate buttons based on JSON data and display corresponding output when buttons are clicked. React’s component-based architecture and state management make it easy to create interactive user interfaces.

Setting Up the Project

Before we begin, make sure you have Node.js and npm (Node Package Manager) installed. To set up the project, follow these steps:

  1. Create a new React project:

    npx create-react-app dynamic-webpage
    cd dynamic-webpage
    
  2. Inside the src folder, create a file named data.json and add your JSON data.

Loading JSON Data

To load JSON data in a React component, we’ll use the fetch API. Here’s how you can do it:

import React, { useState, useEffect } from 'react';

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch('data.json');
        const jsonData = await response.json();
        setData(jsonData);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    }

    fetchData();
  }, []);

  // ... rest of the component
}

The useEffect hook is used to fetch the JSON data when the component mounts. We store the data in the component’s state using the useState hook.

Creating Buttons

Next, we’ll map over the data array to create buttons based on the JSON data:

function App() {
  // ... state and useEffect

  return (
    <div>
      {data.map(item => (
        <button key={item.id}>{item.name}</button>
      ))}
    </div>
  );
}

Each button’s text content is set to the name value from the JSON data, and a unique key is provided for React’s internal reconciliation process.

Handling Button Clicks

To handle button clicks and display output, we’ll modify the App component as follows:

function App() {
  // ... state and useEffect

  const [selectedButtons, setSelectedButtons] = useState([]);
  const [outputText, setOutputText] = useState('');

  const handleButtonClick = (output) => {
    if (!selectedButtons.includes(output)) {
      setSelectedButtons([...selectedButtons, output]);
    } else {
      setSelectedButtons(selectedButtons.filter(item => item !== output));
    }
  };

  useEffect(() => {
    setOutputText(selectedButtons.join(' '));
  }, [selectedButtons]);

  return (
    <div>
      {data.map(item => (
        <button
          key={item.id}
          onClick={() => handleButtonClick(item.output)}
          className={selectedButtons.includes(item.output) ? 'selected' : ''}
        >
          {item.name}
        </button>
      ))}
      <div id="output">{outputText}</div>
    </div>
  );
}

In this code, we manage the selected buttons and output text using React state. The handleButtonClick function adds or removes the clicked button’s output from the selectedButtons state. The useEffect hook updates the outputText state whenever the selected buttons change.

Conclusion

Congratulations! You’ve successfully created a dynamic webpage in React that generates buttons from JSON data and displays output based on user interactions. React’s component-based structure and state management simplify the process of building interactive user interfaces.

For more advanced concepts and features, consider exploring React’s documentation, state management libraries like Redux, and additional front-end development resources.

Keep your curiosity going.Explore more React →
287 TUTORIALS · 22 TOPICSREADY