Advanced React Hacks 2/10 - Dynamic JSX
What if you want a data driven application that renders JSON (not HTML obviously, always BBCode!) as JSX?
export const Component = ({ children }: { children: ReactNode }) => {
const isArray = Array.isArray(children);
return (
<>
{!isArray && children}
{isArray &&
children.map((child, index) => {
return <div key={index}>{child}</div>; // do stuff to the child here
})}
</>
);
};
Now you can use it
import { Component } from "./Component";
export default function App() {
return (
<div>
<Component>test</Component>
<Component>
<div>test2</div>
<div>test3</div>
</Component>
<Component>
<div>test4</div>
<div>test5</div>
</Component>
</div>
);
}
https://codesandbox.io/p/sandbox/cranky-haslett-749y8y
Hope this helps someone!