79719070

Date: 2025-07-29 18:25:16
Score: 0.5
Natty:
Report link

More efficient and cleaner way

const Bar = () => <div>Bar</div>;
const Baz = () => <div>Baz</div>;

const componentMap = {
    bar: Bar,
    baz: Baz,
};

const Foo = ({ iconId }) => {
    const ComponentToRender = componentMap[iconId];

    if (!ComponentToRender) {
        // Fallback: render nothing or a message
        return <div style={{ color: 'red' }}>Component not found for iconId: {iconId}</div>;
    }

    return <ComponentToRender />;
};

const EntireApp = () => (
    <div>
        <div>Some other important content</div>
        <Foo iconId="foz" /> {/* Invalid iconId won't crash the app */}
    </div>
);

Why better?

  1. O(1) lookup instead of O(n).
  2. Avoids .find() completely
  3. More readable for large mappings
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: Santhosh