简体   繁体   中英

hide and show names using react hooks

  • I am new to react hooks,
  • in my app initially, all the names of the users should be hidden.
  • later when I click each user it should show the name.
  • so I used the show and setshow.
  • when I tried to print the values in the browser, I don't see it. return(<div>{show}users Data{setShow}
  • I wrote click for each user but I am not sure how to hide and show.
  • there will be millions of users in my app, so whats the best way to hide and show the name when I click each
  • providing my code snippet and sandbox below

https://stackblitz.com/edit/react-t1mdfj?file=index.js

import React, { Component, useState } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";

function DataClick(){
  const [show, setShow]= useState(false);

  function showItem(e){
    console.log("e--->", e.target);
    setShow(true);
  }
  return(<div>{show}users Data{setShow}
  <div onClick= {showItem}
  //onClick={()=>setShow(true)}
    >user1</div>
    <div>John</div>
  <div onClick= {showItem}
  //onClick={()=>setShow(true)}
    >user2</div>
    <div>Mike</div>

    <div onClick= {showItem}
  //onClick={()=>setShow(true)}
    >user3</div>
    <div>Mike3</div><div onClick= {showItem}
  //onClick={()=>setShow(true)}
    >user4</div>
    <div>Mik4e</div><div onClick= {showItem}
  //onClick={()=>setShow(true)}
    >user5</div>
    <div>Mike5</div><div onClick= {showItem}
  //onClick={()=>setShow(true)}
    >user6</div>
    <div>Mike6</div><div onClick= {showItem}
  //onClick={()=>setShow(true)}
    >user7</div>
    <div>Mike7</div><div onClick= {showItem}
  //onClick={()=>setShow(true)}
    >user8</div>
    <div>Mike8</div>

  </div>);
}



render(<DataClick />, document.getElementById("root"));

@computer cool, Please see the below implementation to show and hide the usernames when user id is clicked, this is an updated code of @JMadelaine's implementation. Hope this will help. (In @JMadelaine's implementation one drawback I found is, once the username is shown it was not hiding back when clicking on the user id again because he was always setting the state to true onClick), please see the below code.

import React, { Component, useState } from "react";

const UserItem = ({ user }) => {
  const [isNameShown, setIsNameShown] = useState(false)

  const handleChange = () => {
    setIsNameShown(prevState => !prevState)
  }

  return (
    <div onClick={handleChange} >
      <div>{user.id}</div>
      {isNameShown && <div>{user.name}</div>}
    </div>
  )
}

function DataClick() {
  const users = [
    {
      id: 'user1',
      name: 'John',
    },
    {
      id: 'user2',
      name: 'Peter',
    },
  ]

  return (
    <div>
      {users.map(user => <UserItem user={user} />)}
    </div>
  )
}


export default DataClick;

Here the handleChange function sets the value of the state using the previous value by passing a callback function instead of direct value, so this callback function will get the previous state as argument and returns the inverted value, so if the user is opened, it will close, if the user is closed it will open.

EDIT: Below is the explanation of the code setIsNameShown(prevState => !prevState)

setIsNameShown or any function that is returned by the useState hook can be written in the below ways.

1st way example:

setIsNameShown(false)

in this, you are directly passing the value to be set irrespective of the previous value.

2nd way example:

setIsNameShown((prevStateVariable) => {
    return !prevStateVariable
})

or more concisely this same can be written as

setIsNameShown(prevStateVariable => !prevStateVariable)

in this case, the function setIsNameShown accepts the callback function which receives the previous state (to which the function is related to) as an argument. So in cases where you need to set values to state which depends on the previous state value, use the callback function instead of directly providing the value.

The useState hook is just like a class component's state and setState . In your case show is the state variable that has a true or false value, and you can change this value using the function setShow .

To conditionally show the users' names, you should use the value of show like so:

return(
  <div>
    <div onClick={() => setShow(true)}>user1</div>
    {show && <div>John</div>}
    <div onClick={() => setShow(true)}>user2</div>
    {show && <div>Mike</div>}
  </div>
)

However, I don't think that is what you want. It sounds like you want to show only the name of the user that was clicked, and in the current state, when you click one user, all usernames will show because they all depend on the same state variable show .

You should create a separate component that contains the logic to show and hide a username, and map each user to that component. That way, each user has their own show state.


EDIT:

I've updated your code with the below:

// each user gets mapped to this component
const UserItem = ({user}) => {
  // that means each user has their own 'isNameShown' variable
  const [isNameShown, setIsNameShown] = useState(false)

  return (
    // if you click this div, this user's isNameShown value will be set to true
    <div onClick={() => setIsNameShown(true)}>
      // user.id is the id of the user from props
      <div>{user.id}</div>
      // only show this user's name if this user's isNameShown is true
      {isNameShown && <div>{user.name}</div>}
    </div>
  )
}

function DataClick(){

  // we just create some example users here for testing
  const users = [
    {
      id: 'user1',
      name: 'John',
    },
    {
      id: 'user2',
      name: 'Peter',
    },
  ]

  return(
    <div>
      // map each user to a UserItem, passing the user as a prop
      {users.map(user => <UserItem user={user} />)}
    </div>
  )
}

I don't know what your users data structure looks like, so you should change it accordingly.

Something to learn here is that, if you find yourself repeating code over and over or copy pasting things again and again, then there is usually a better way of achieving what you want. Your list of users was basically copied and pasted over and over again, so you should create a single UserItem component instead.

There may be on issue with this code, which is that once a username is visible, you cannot hide it again, but I'll let you figure out how to do that if that is your intention.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM