-1

I want to render the component in the map method by using a state value from db

example: -

const [post, setPost] = useState([]);

     <>
        {post.map((ce) => (
          <div key={ce._id}>
            <h2>{ce.tittle}</h2>
            <p>{ce.content}</p>
            <{ce.component}/>   /// i don't no it's right or wrong.
          </div>
        ))}
      </>
isherwood
  • 58,414
  • 16
  • 114
  • 157
MR_HACK
  • 13
  • 1
  • 5
  • What is `ce.component`? Is it an actual React component? Is it just a string? Something else? This doesn't seem to have anything to do with state and everything to do with what you're trying to render and what data you have to specify it. Can you update your example to reflect this? – David Sep 28 '21 at 16:25
  • I just want to add a different - different component on the frontend by using data base value for eg :- i import a header component in my code and i want to show it on frontend by db – MR_HACK Sep 28 '21 at 16:29
  • 2
    I assume that you're dynamically specifying what component is held in that property. There's probably a better way to conditionally include your component. You might expand the scope of your post to avoid an [XY question](http://xyproblem.info). – isherwood Sep 28 '21 at 16:30
  • Does this answer your question? [Dynamic tag name in jsx and React](https://stackoverflow.com/questions/33471880/dynamic-tag-name-in-jsx-and-react) – David Sep 28 '21 at 16:34

1 Answers1

1

Interesting, i think it can be done. But according to React, it has to have a uppercase letter.

     <>
        {post.map((ce) => {
          const Comp = ce.component
          return (
            <div key={ce._id}>
              <Comp /> 
            </div>
          )
        ))}
      </>

What's inside ce.component is important. What's supported, according to doc is a function component such as the following.

  const Comp = () => <div>Hello</div>
windmaomao
  • 7,120
  • 2
  • 32
  • 36