Conceal and reveal identities with the power of react hooks

  • I'm just starting to work with React hooks,
  • In my app, I want all user names to be hidden by default.
  • However, when I click on each user, their name should be displayed.
  • To accomplish this, I am using the show and setShow functions.
  • Although when I try to display the values in the browser, they do not appear as expected.
    return(<div>{show}users Data{setShow}
  • I have set up a click function for each user, but I am unsure how to properly hide and show the names.
  • Since there will be millions of users in my app, I am looking for the most efficient way to toggle the visibility of each name on click.
  • Below you can find my code snippet and a sandbox link for reference

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"));

Answer №1

@computer cool, Check out the updated code below for a feature that allows users to show and hide usernames by clicking on their user id. This code is an improvement on @JMadelaine's implementation where there was a drawback of not being able to hide the username back when clicking on the user id again. Take a look at the code snippet:

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;

The key function here is handleChange which toggles the state based on its previous value rather than setting it directly to true or false. This ensures that clicking on the user id will either show or hide the username depending on its current state.

EDIT: To elaborate on the code

setIsNameShown(prevState => !prevState)

Functions like setIsNameShown returned by the useState hook can be implemented in different ways.

Example of the 1st way:

setIsNameShown(false)

In this approach, the value is set directly without considering the previous state.

Example of the 2nd way:

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

Or more succinctly:

setIsNameShown(prevStateVariable => !prevStateVariable)

In this scenario, the function accepts a callback argument that provides the previous state allowing for state updates that depend on the previous state value. It's recommended to use this approach when the new state depends on the existing one.

Answer №2

The concept of the useState hook is similar to a class component's use of state and setState. In this scenario, the state variable show contains either a true or false value, which can be altered using the function setShow.

In order to selectively display users' names, you need to utilize the value of show in the following manner:

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

Nevertheless, it appears that this may not align with your intended outcome. It seems like your goal is to only reveal the name of the user that was clicked on. Presently, upon clicking any user, all usernames are displayed simultaneously due to their reliance on the same state variable show.

The recommended approach would involve creating a distinct component responsible for toggling the visibility of a username, and then associating each user with that component. By doing so, every user will possess their individual show state.


EDIT:

Your code has been enhanced as shown below:

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

  return (
    // when this div is clicked, the 'isNameShown' value for this user becomes true
    <div onClick={() => setIsNameShown(true)}>
      // user.id represents the user's id from props
      <div>{user.id}</div>
      // reveals this user's name solely if their 'isNameShown' value is true
      {isNameShown && <div>{user.name}</div>}
    </div>
  )
}

function DataClick(){

  // example users created here for testing purposes
  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>
  )
}

It is advised to adjust the structure of your users data according to your specific requirements.

An important takeaway from this exercise is that repetition or unnecessary duplication of code usually indicates room for improvement in achieving desired results. Your list of users was essentially duplicated multiple times, suggesting the necessity for a singular UserItem component instead.

A potential issue within this code snippet could be the inability to hide a displayed username once visible. I leave it up to you to address this concern should it align with your objectives.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to toggle the navigation bar between opened and closed

I'm having trouble with this navbar not opening and closing properly. Can anyone suggest what script I should add? <nav class="navbar navbar-expand-md"> <a class="navbar-brand" href="/"> <img src=&qu ...

How can the "not selected" option be disabled in a Vue Select component?

I have implemented a select box in the following manner: JS: Vue.component("v-select", VueSelect.VueSelect); new Vue({ el: "#app", data: { options: [ { countryCode: "AU", countryName: "Australia" }, { countryCode: "CA", countryName: " ...

"Labeling Text Styling in HTML5 Without Using the Font Tag

As I have a label tag and want to change part of the text's font within that label, I am facing a challenge. Previously, I used the font tag for this purpose. However, with its exclusion in HTML5, I am unsure about how to achieve this effect now. The ...

Using the CSS background position of 50% 50% is not effective

Is it possible to create a background in CSS for an element with unknown width and height that starts at the center and repeats? This is what I would like to achieve: This is the code I have written: body { background: url('http://www.lighthouse ...

Instructions for removing a class using the onclick event in JavaScript

Is there a way to make it so that pressing a button will display a specific class, and if another button is pressed, the previous class is removed and a new one is shown? Thank you for your assistance. function myFunction() { document.getElementById ...

"Troubleshooting: Why is the 'RectAreaLightHelper' not moving correctly in React-three-fiber

Issue Overview: I have noticed that the rectAreaLight behaves differently compared to other light helpers in my project. Despite using the "useHelper" function and placing it in the "three/examples" folder, the position of the rectAreaLight does not change ...

An error occured upon loading FullCalendar: Uncaught TypeError - Unable to read property 'push' as it is undefined

First of all, thank you for your assistance. I've been trying to load FullCalendar (https://fullcalendar.io/) on my development environments but it doesn't seem to be working. When I check the console in Chrome, it shows me the following error m ...

Steps for setting up Autocomplete feature with all choices pre-selected

I am working with an Autocomplete component that includes a "Select All" feature. My goal is to have all options selected by default when the component loads, in addition to the "Select All" option. I have attempted setting the defaultValue to my initial ...

How can you ensure that only one dropdown is active at a time while keeping others inactive in a React component

I'm currently working on implementing a dropdown navigation feature. The goal is to ensure that only one dropdown remains open at a time when clicked, and all others should close automatically. However, I've run into an issue where both dropdowns ...

Revamping a user interface to handle clicks and display using Blazor instead of JavaScript

As a newcomer to Blazor, I find myself searching for the most efficient method to replicate a JavaScript-based click and display user interface that I had previously created. The code snippet for the page is as follows: <div class="container"> & ...

What is the best way to implement a timer or interval system in React and Next.js that continues running even when the tab is not in focus or the browser is in

I am attempting to create a stopwatch feature using next js. However, I have encountered an unusual issue where the stopwatch does not function correctly when the tab is not focused or when the system goes to sleep or becomes inactive. It appears that the ...

Utilizing AJAX to submit a combination of text fields and files in an HTML form

Just starting out with AJAX and JQuery, I'm curious if it's possible to send data from an HTML form, including a text file and two separate text boxes, via an AJAX request. So far, I've managed to send the data from the text boxes but not th ...

Discovering nearby intersections within 2 sets of arrays

Imagine having these two arrays: var a = [126, 619, 4192, 753, 901]; var b = [413, 628, 131, 3563, 19]; Is there a way to identify elements in both arrays that are close to each other by a certain percentage? Let's say we have the following functio ...

Arrange content in rows using flexbox - 2 rows on mobile devices, 3 rows on desktop screens

I'm currently working on setting up my flexbox layout to display 3 columns on larger screens and 2 columns on smaller mobile screens (refer to images 1 and 2 below). You can check out my JS Fiddle and code snippets: https://jsfiddle.net/kwxj83v6/6/ ...

Creating Apache Arrow vectors in TypeScript for writing data to a Table

Currently, I am in the process of creating a method that is designed to take a column of data, referred to as data: any[], and then pack it into an Arrow-typed Array Buffer for insertion into an Arrow table. To illustrate with an example, if we consider T ...

ng-view or controller appears to be malfunctioning

I'm currently working on a small web application using AngularJS. I have an index.html file in the main directory and three other HTML pages within the html subdirectory. login.html list.html detail.html Initially, the index.html should load the ...

The Bootstrap CSS styles seem to be malfunctioning following the upgrade from Angular 4 to Angular 5

Developed a Single Page Application with Angular 4 and .NET Core 2, integrated with Bootstrap for styling. However, upon upgrading from Angular 4 to Angular 5, the Bootstrap styling disappeared. It seems that the bootstrap.css file is not being loaded cor ...

Guide on redirecting from your under-construction website to an Android app installed on your mobile device

I am in the process of developing an online shopping platform and I am looking to add a specific feature: I would like my website to be able to launch a pre-installed app on my phone from the Google Play Store when a user clicks on an image/button. Alter ...

Unable to access socket.io after modifying the application's URL

There's been a lot of discussion surrounding this topic, but most of it doesn't apply to my situation since I am using express 4.16.4 and socket.io 2.2.0. Also, my example is already functional on both localhost and remote hosting. When setting ...

When I scroll down, the <div> below the <header> disappears, but only the header should be invisible. Can anyone explain why this is happening?

Check out this JsFiddle link for reference. I have implemented the Material Design Lite framework in my project. In the header section, I want to include a Title row, a row that displays a description (labeled as Story followed by some text), and a row fo ...