Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To convert JSON object to string in react js, use the JSON.stringify() method it will return the object as a string, and then you can do as you want like sending through API or storing in local storage.

In the following example, we will take the JSON object example and convert it into a string.

let obj = {id: 1, name: "infinitbility"};

console.log(JSON.stringify(obj)) // '{"id":1,"name":"infinitbility"}'

Today, I’m going to show you How do i convert a JSON object to a string in react js, as above mentioned here, I’m going to use the JSON.stringify() function.

Let’s start today’s tutorial how do you convert JSON object to string in react js?

In this example, we will do

  1. take an example of object state
  2. convert it into a string
  3. store in local storage
  4. print the JSON object string on the page screen
import React, { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
  const [sampleObject, setSampleObject] = useState({
    id: 1,
    name: "infinitbility"
  });

  useEffect(() => {
    let sampleString = JSON.stringify(sampleObject);
    localStorage.setItem("sampleString", sampleString);
    console.log(sampleString);
  }, []);
  return (
    <div className="App">
      <h1>{JSON.stringify(sampleObject)}</h1>
    </div>
  );
}

In the above examples, we have taken the sample object state, convert it into a string, stored it in localStorage, and print it on the screen.

I hope it’s help you, All the best 👍.