Search code examples
reactjsarraysdictionarycomponents

I can't render my component dynamically in react using the map function


I'm currently learning react but for a reason I don't understand what I am doing wrong , I am trying to generate components dynamically using the map function on a array to render the components . here's my code , I didn't find what I was looking for on the internet , thanks for your help . here's the errors that my console is returning me :

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

I also followed a bunch of tutorials and they all seems to be doing exactly like this also when I try to render the components using only the props of the objects of the array and putting it into a native dom element it is perfectly working .

import React from "react";
import "./index.css"
import  ReactDOM  from "react-dom/client";


function App() {
  
  const array  = [

        {
            setup:"c'est un setup",
            punchline:"c'est une punchline"
        },
        {
            setup:"c'est un setup",
            punchline:"c'est une punchline"
        },
        {
            setup:"c'est un setup",
            punchline:"c'est une punchline"
        },
        {
            setup:"c'est un setup",
            punchline:"c'est une punchline"
    
        },
       
    ]

const joke = array.map( Joke =>{

    
    return(
        
        <Joke setup={Joke.setup} punchline={Joke.punchline}/>
        
        )
        
    }
    
    )
    
    console.log(array);




return(
 
    
    
    <div>

    {joke}

    </div>

    
)















}


let root = ReactDOM.createRoot(document.querySelector("#root"));
root.render(<App/>);

Solution

  • import React from "react";
    import ReactDOM from "react-dom/client";
    
    export default App = () => {
      const array = [
        {
          setup: "c'est un setup",
          punchline: "c'est une punchline"
        },
        {
          setup: "c'est un setup",
          punchline: "c'est une punchline"
        },
        {
          setup: "c'est un setup",
          punchline: "c'est une punchline"
        },
        {
          setup: "c'est un setup",
          punchline: "c'est une punchline"
        }
      ];
    
      // This is possible
      // const jokes = array.map((joke) => {
      //   return <Joke setup={joke.setup} punchline={joke.punchline} />;
      // });
    
      // This is cleaner
      return (
        <div>
          {array.map((joke) => {
            return <Joke {...joke} />;
          })}
        </div>
      );
    };
    
    
    

    This should do the job.