Search code examples
reactjsmappingjsxconditional-operatorconditional-rendering

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:

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>)
    }