2

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?

1
  • component must be capitalized => Component. Change the name of your prop. Lowercase component names are not allowed as they get confused with the native elements like div, or p. Commented Sep 1, 2022 at 19:14

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.