Search code examples
javascriptreactjsjsxmap-functionreact-context

Rendering HTML from map function in React Context API render function


I'm trying to render out a list of titles by calling map on state from inside the <MyContext.Consumer> component but the code is not returning the list items. However, if I do a console.log(dataImTryingToMap); it shows exactly what I'm trying to render. The <ul> is rendered but no <li>'s are. There are no errors thrown by create-react-app. What am I missing??? Here is the consumer component:

<MyContext.Consumer>
    {context => (
        <ul>
            {Object.keys(context.state.subjects).map(subject => {
                <li>{context.state.subjects[subject].title}</li>;
                console.log(context.state.subjects[subject].title);
             })}
        </ul>
    )}
</MyContext.Consumer>

The console log returns exactly the data I'm looking for, but nothing shows on the screen.

And here is the state from the <MyContext.MyProvider> component:

state = {
    subjects: {
        subject0: {
            title: "Math",
            description: "",
            cards: {
                card1: {
                    note: "",
                    answer: ""
                }
            }
        },
        subject1: {
            title: "history",
            description: "",
            cards: {
                card1: {
                    note: "",
                    answer: ""
                }
            }
        }
    }
};

Thanks for any help!


Solution

  • You are not returning anything from the Array.map() callback:

    {Object.keys(context.state.subjects).map(subject => {
        <li>{context.state.subjects[subject].title}</li>; <-- this is not returned
        console.log(context.state.subjects[subject].title);
     })}
    

    const contextValue = { state: {"subjects":{"subject0":{"title":"Math","description":"","cards":{"card1":{"note":"","answer":""}}},"subject1":{"title":"history","description":"","cards":{"card1":{"note":"","answer":""}}}}}};
    
    
    const MyContext = React.createContext();
    
    const Example = () => (
      <MyContext.Consumer>
      {context => (
        <ul>
        {Object.keys(context.state.subjects).map(subject => {
          console.log(context.state.subjects[subject].title);
          return (
            <li key={subject}>{context.state.subjects[subject].title}</li>
          );
         })}
        </ul>
      )}
      </MyContext.Consumer>
    );
    
    const Demo = ({ value }) => (
      <MyContext.Provider value={value}>
        <Example />
      </MyContext.Provider>
    );
    
    ReactDOM.render(
      <Demo value={contextValue} />,
      demo
    );
    <script crossorigin src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
    
    <div id="demo">
      </demo>