Categories
React Answers

How to Display JSON Output Using React?

Spread the love

Sometimes, we want to display JSON output in our React components.

In this article, we’ll look at how to display JSON output in our React components.

Display JSON Output Using React with the JSON.stringify Method

We can display JSON output in our React components with the JSON.stringify method.

For instance, we can write:

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

export default function App() {
  const [json, setJson] = useState({});

  const getJSON = async () => {
    const res = await fetch("https://yesno.wtf/api");
    const data = await res.json();
    setJson(data);
  };

  useEffect(() => {
    getJSON();
  }, []);

  return <div className="App">{JSON.stringify(json)}</div>;
}

to create the json state with the useState hook.

Then we create the getJSON function to call fetch to get the JSON data we want to display.

We call res.json to turn the JSONM response string into a JavaScript object.

Then we call setJson to set data as the value of the json state.

Next, we have the useEffect hook to run getJSON when the component mounts.

And then in the JSX, we call JSON.stringify to stringify the json object so that we can render it on the screen.

We can only render strings or JSX on the screen.

Conclusion

We can display JSON output in our React components with the JSON.stringify method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *