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!

Sunday, January 21, 2024

Advanced React Hacks 1/10 - Conditional Hooks

Advanced React Hacks 1/10 - Conditional Hooks

 According to react.dev "Rules of Hooks" you cannot call hooks inside a condition

https://react.dev/warnings/invalid-hook-call-warning#breaking-rules-of-hooks

But what if you want it?


Use components!

export const ParentComponent = ({ component }: ParentComponentProps) => {

  /* derive condition here */
  // const condition = false;
  const condition = true;

  /* derive property here */
  // cont property = 0;
  // ...

  return (<>
    {
      condition && <HookComponent hookProperty={property} />
    }
  </>);
}

export const HookComponent = ({ hookProperty }: ChildComponentProps) => {
  useCustomHook(hookProperty); // could be anything!
  return <></>; // yes, components can render nothing
}

With great power comes great responsibility!

Hope this helps! More next time...