Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating generic components in React Javascript

I’m trying to build a React select component that can support multiple different child component types.

I’d like to do something like this:

export const GenericSelect = (props) => {
  const { component, items } = props;
  return <>{items && items.map((item, index) => <component id={items.id} name={item.name} />)}</>;
};

And then be able to use it like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<GenericSelect component={NonGenericCard} items={items} />

Where NonGenericCard supports a fixed set of properties (e.g., id, name), which will be populated from values in the items object.

I tried this, but it doesn’t seem like it can create the <component/> at run-time.

Is this possible in Javascript? If so, how can it be accomplished?

>Solution :

In JSX, lower-case tag names are considered to be HTML tags. So you should use Component instead of component.

Also id should be item.id instead of items.id and you should give each element a key.

export const GenericSelect = (props) => {
  const { Component, items } = props;
  return (
    <>
      {items &&
        items.map((item, index) => (
          <Component key={item.id} id={item.id} name={item.name} />
        ))}
    </>
  );
};
<GenericSelect Component={NonGenericCard} items={items} />

https://reactjs.org/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading