Skip to content

Instantly share code, notes, and snippets.

@alemantrix-settyl
Created September 7, 2023 16:10
Show Gist options
  • Save alemantrix-settyl/1852926d080c1e70efcf3849c8c88c7f to your computer and use it in GitHub Desktop.
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)
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