Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using a ternary operator to render conditionally by mapping through an array

I am attempting to conditionally render items of an array from json placeholder, by using a ternary operator to establish if an array has any items, then map through it, and return the items. If not, return a message indicating so. I’ve searched to see if/where my syntax is wrong to no avail.

Here’s what I have:

import React, { useEffect, useState } from "react";
import { fetchUsers } from "../../lib/functions";

const Users = () => {
    const [users, setUsers] = useState([]);

    useEffect(() => {
        fetchUsers().then(res => setUsers(res.data))
    }, []);
    return (
        <div className="users">
            <h1>Users</h1>
            {users.length ? users.map((user) => {
                (<div key="id">
                    <h4>{users.name}</h4>
                    <h5>{users.email}</h5>
                    <h6>{users.username}</h6>
                    <p>{users.address}</p>
                </div>) :
                (
                    <div>
                        <p>User not found.</p>
                    </div>
                )})}
        </div>
    );
}


export default Users;

It’s throwing me this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ERROR in [eslint]
src/components/users/Users.js
Line 19:23: Parsing error: Missing semicolon. (19:23)

webpack compiled with 2 errors

>Solution :

It seems your use of the ternary operator is wrong.
Only first div should be in the map but according to your code, both of div are in the map.

{users.length ? users.map((user) => 
  (<div key="id">
    <h4>{users.name}</h4>
    <h5>{users.email}</h5>
    <h6>{users.username}</h6>
    <p>{users.address}</p>
  </div>))
  :
  (<div>
    <p>User not found.</p>
  </div>)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading