Home > Back-end >  Creating generic components in React Javascript
Creating generic components in React Javascript

Time:09-02

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:

<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?

CodePudding user response:

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

  • Related