skip to Main Content

My Dashboard component is a arrow function as shown below

const Dashboard= (props) => { 


//users object is fetched

    return(

        <ul>
            {
                Object.keys(users).forEach((key,index) => {
                    console.log("iterating------>"+users[index].name);//this is iterating
                    return  <li key={key}>hello</li>//this is not rendering
                })
            }
            
        </ul>
    )



}

This way it is not rendering to html. Please help

Tried my best but didn’t get the expected output

3

Answers


  1. Use map instead of forEach and it should work

    Here’s the corrected code:

    const Dashboard = (props) => { 
    //users object is fetched
    
    return (
        <ul>
            {
                Object.keys(users).map((key, index) => {
                    console.log("iterating------>" + users[key].name); // Log each user
                    return <li key={key}>hello {users[key].name}</li>; // Render <li> for each user
                })
            }
        </ul>
    );
    }
    

    Or use this (I prefer and use):

    const Dashboard = (props) => { 
    //users object is fetched
    
    return (
        <ul>
            {
                Object.keys(users).map((key, index) => (
                   
                     <li key={key}>hello {users[key].name}</li>; // Render <li> for each user
                ))
            }
        </ul>
    );
    }
    

    Hope this helps…

    Login or Signup to reply.
  2. You are using forEach inside the JSX which does not return anything. In React to render a list you should use map instead that way it returns a new array that React can render as JSX elements.
    You can use this example instead

    const Dashboard = ({ users }) => {
        return (
            <ul>
                {Object.keys(users).map((key) => (
                    <li key={key}>{users[key].name}</li>
                ))}
            </ul>
        );
    };
    
    Login or Signup to reply.
  3. <ul>{Object.values(users).map(({id, name, ...restUserProps}) => (<li key={id}>{name}</li>))}</ul>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search