Saturday, January 27, 2024

Advanced React Hacks 2/10 - Dynamic JSX

 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?



One way is React.Children


Instead do this,

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>
  );
}

(Wow pasting from CodeSandbox worked!)

https://codesandbox.io/p/sandbox/cranky-haslett-749y8y

Hope this helps someone!

No comments:

Post a Comment