I have a JSON
object which is deeply nested. I want to display input fields with respect to the JSON values. To traverse through the deeply nested JSON object I used recursion and collected all processed input fields to set it into a state to display in the main return of the module. However, it is throwing Too many re-renders to infinite loop. Uncaught run time errors
.
I have tried various methods such as,
-
Storing
displayFrom
indisplayProperties
in a separate const and used thatconst
intosetDisplayForm
. -
Applied various conditions in the main return of App module such as
typeof properties[ key ] === 'object'
in the conditional rendering -
Used
useMemo
to wrap thedisplayProperties
function from causing too many re-render issue.
I have implemented the same in stackblitz please take a look at my code and comment. https://stackblitz.com/edit/vitejs-vite-kjyz2y?file=src%2FApp.jsx&terminal=dev
There is an const input
it makes the code looks bigger and complex but it is just a JSON nested object. The actual logic and code looks like below,
import { useState } from 'react';
import reactLogo from './assets/react.svg';
import viteLogo from '/vite.svg';
import './App.css';
function App() {
const [displayFrom, setDisplayForm] = useState();
const input = {} // a deeply nested JSON object
const displayProperties = (properties) => {
return (
<>
{Object.keys(properties).map((key, index) => (
<div key={index}>
<span>{key === 'label' ? properties[key] : null}</span>
<span>
{JSON.stringify(properties[key]).includes('properties') ||
JSON.stringify(properties[key]).includes('label')
? displayProperties(properties[key])
: null}
</span>
</div>
))}
</>
);
};
const builtForm = () => displayProperties(input);
setDisplayForm(builtForm);
return <>{displayFrom}</>;
}
export default App;