ShakaCode | ShakaCode Blog | Rails On Maui Blog | Rails | ReactJs | JavaScript | Webpack | Productivity |

React - How to show only the clicked user

In the following app, I’m accessing the random user API and shows a list of 12 users.

App.js

import React, { useState } from 'react'
import UserList from './components/UserList'

const App = props => {
  const [id, setID] = useState(null)
  console.log(`Passed variable to App.js is: ` + id)

  return (
    <>
      <UserList setID={setID} />
    </>
  )
}

export default App

UserList.js

import React, { useState, useEffect } from 'react'
import axios from 'axios'

const UserList = ({ setID }) => {
  const [resources, setResources] = useState([])

  const fetchResource = async () => {
    const response = await axios.get(
      'https://api.randomuser.me/?results=12'
    )
    setResources(response.data.results)
  }

  useEffect(() => {
    fetchResource()
  }, [])

  return (
    <ul className="card__wrapper">
      {resources.map(item => (
        <li className="card" key={item.name.first}>
          <div className="card__item">
            <h2 className="card__title">{item.name.first} {item.name.last}</h2>
            <button
              className="card__cta"
              onClick={() => setID(item.login.uuid)}
            >
              Details
            </button>
          </div>
        </li>
      ))}
    </ul>
  )
}

export default UserList

The above code is working. But now I want that if I click on the button for any of those listed users, only that user get showed.

How can I do that?

To do that, first you need to share selected id with UserList component:

App.js

Then update UserList accordingly:

UserList.js

const UserList = ({ id, setID }) => {

return (
    <ul>
      { resources
           .filter(user => Boolean(id) ? user.login.uuid == id : true )
           .map(item => (
           <li key={item.name.first}>
             <div>
               <h2>{item.name.first} {item.name.last}</h2>
               { Boolean(id) ? 
                 <button onClick={() => setID(null)}>
                   Hide
                 </button>
                 :
                 <button onClick={() => setID(item.login.uuid)}>
                   Details
                 </button> 
                }
             </div>
           </li>
          )
      }  
    </ul>
)

}