Sometimes, we want to render a string as React component.
In this article, we’ll look at how to render a string as React component.
How to render a string as React component?
To render a string as React component, we can put the components we want to render in an object.
Then we can render the components by accessing them from the object with a string as the key.
For instance, we write:
import React from "react";
const Foo = () => <p>foo</p>;
const Bar = () => <p>bar</p>;
const Components = {
Foo,
Bar
};
const FooComponent = Components["Foo"];
export default function App() {
return <FooComponent />;
}
We have the Foo
and Bar
components.
And we put them Foo
and Bar
into the Components
Object.
Next, we access the Foo
component from Components
with:
const FooComponent = Components["Foo"];
And finally, we render it with <FooComponent />
.
Conclusion
To render a string as React component, we can put the components we want to render in an object.
Then we can render the components by accessing them from the object with a string as the key.