Created
September 7, 2023 16:10
-
-
Save alemantrix-settyl/1852926d080c1e70efcf3849c8c88c7f to your computer and use it in GitHub Desktop.
Recursively render a react component based on an object keys (nested will work too)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "./styles.css"; | |
export default function App() { | |
let data = { | |
fqNumber: "FQ42523424", | |
fqStatus: "Active", | |
fqDate: "xyz date", | |
nested: { | |
test: "This is just a test value" | |
}, | |
more: { | |
nest: { | |
dtt: "xzy" | |
} | |
} | |
}; | |
let selector = { | |
fqNumber: "FQ Number", | |
fqStatus: "fQ Status", | |
"nested.test": "test", | |
"more.nest.dtt": "something" | |
}; | |
function displayTestComponent(dt, obj) { | |
const keys = dt.split("."); | |
function getValue(keys, obj) { | |
const key = keys.shift(); | |
if (key && obj[key]) { | |
return getValue(keys, obj[key]); | |
} | |
return obj; | |
} | |
const value = getValue(keys, obj); | |
return selector[dt] && <TestComponent name={selector[dt]} value={value} />; | |
} | |
return ( | |
<div className="App"> | |
{Object.keys(selector).map((key) => displayTestComponent(key, data))} | |
</div> | |
); | |
} | |
function TestComponent({ name, value }) { | |
return ( | |
<> | |
<h1>{name}</h1> | |
<p>{value}</p> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment