Home > database >  Rendering an object into a table in React
Rendering an object into a table in React

Time:06-15

I am a React beginner and I am having trouble with rendering an object into a table. I can access the ctx object with console.log but I cannot display it on the browser in the table. If anyone can help me please give me your advice. the code is below.

The goal is to display data from the object(ctx) into the table.

function AllData(){
const ctx = {users:[{name:'john', email:'[email protected]', passwords:'password'},{name:'smith', email:'[email protected]', passwords:'password']};
const userdata = ctx.users.map((user)=>{    
    (
    <tr>
        <td>{user.name}</td>
        <td>{user.email}</td>
        <td>{user.password}</td>
    </tr>
    )
});

return (
  
         <table className="table">
             <thead>
                 <tr>
                    <th scope="col">Name</th>
                    <th scope="col">Email</th>
                    <th scope="col">Password</th>
                 </tr>
             </thead>
             <tbody>
                {userdata}
             </tbody>
         </table>
     )}

CodePudding user response:

You need to return something from the .map like

const userdata = ctx.users.map((user) => {
    return (
        <tr key={user.name}>
            <td>{user.name}</td>
            <td>{user.email}</td>
            <td>{user.password}</td>
        </tr>
    )
});

Or even just

const userdata = ctx.users.map((user) => (
    <tr key={user.name}>
        <td>{user.name}</td>
        <td>{user.email}</td>
        <td>{user.password}</td>
    </tr>
));

Another option would be like

return (
    <table className="table">
        <thead>
            <tr>
                <th scope="col">Name</th>
                <th scope="col">Email</th>
                <th scope="col">Password</th>
            </tr>
        </thead>
        <tbody>
            {
                ctx.users.map((user) => (
                    <tr key={user.name}>
                        <td>{user.name}</td>
                        <td>{user.email}</td>
                        <td>{user.password}</td>
                    </tr>
                ))
            }
        </tbody>
    </table>
)

Also added the key property, since you are using an array.

CodePudding user response:

Add return inside map

const userdata = ctx.users.map((user)=>{    
    return (
    <tr>
        <td>{user.name}</td>
        <td>{user.email}</td>
        <td>{user.password}</td>
    </tr>
    )
});
  • Related