How to Define Components with Dynamic Names with React and JSX?

Sometimes, we want to define components with dynamic names with React and JSX.

In this article, we’ll look at how to define components with dynamic names with React and JSX.

Define Components with Dynamic Names with React and JSX

To define components with dynamic names with React and JSX, we can put the components in an object.

Then we can access the components with the key from the object.

For instance, we write:

import React from "react";

const PhotoStory = () => <div>photo</div>;

const VideoStory = () => <div>photo</div>;

const components = {
  photo: PhotoStory,
  video: VideoStory
};

const Story = ({ storyType }) => {
  const SpecificStory = components[storyType];
  return <SpecificStory />;
};

export default function App() {
  return <Story storyType="photo" />;
}

to create components object with the PhotoStory and VideoStory components as its property values.

Then in the Story component, we can get the component form the components object with the storyType prop and assign it to SpecificStory.

Finally, we use the Story component in App with the storyType set to 'photo' so we can render the PhotoStory component.

So we see ‘photo’ rendered on the screen.

Conclusion

To define components with dynamic names with React and JSX, we can put the components in an object.

Then we can access the components with the key from the object.