Home > other >  how to revert (last clicked list item) back to its original color when any other item is clicked - r
how to revert (last clicked list item) back to its original color when any other item is clicked - r

Time:05-02

I'm trying to implement this feature in react:

Default state: All list items are blue;

If one specific item is clicked: that same item text color becomes red;

When any other item is clicked: that last item text color revert back to blue;

In my code the item text color stays red, even when other items are clicked.

I searched here and it seems that I should use useRef and the item.id but I'm stuck on how to implement this particular feature.

Thanks

App.js

import { useState } from 'react'
import Item from './components/Item'

function App() {
    const [items, setItems] = useState([
        {
            id: 1,
            name: 'Item 1',
        },
        {
            id: 2,
            name: 'Item 2',
        },
    ])

    return (
        <>
            {items.map((item) => (
                <Item key={item.id} id={item.id} name={item.name} />
            ))}
        </>
    )
}

export default App

Item.jsx

import { useState } from 'react'

function Item({ id, name }) {
    const [clicked, setClicked] = useState(false)
    const handleClick = () => {
        setClicked(!clicked)
    }
    return (
        <>
            <button
                onClick={handleClick}
                style={{ color: clicked ? 'red' : 'blue' }}
                key={id}
            >
                {name}
            </button>
        </>
    )
}

export default Item

CodePudding user response:

You need to maintain the selected id in the parent component and based on the selection we can change the color of the button text.

App.jsx

import { useState } from 'react'
import Item from './components/Item'

function App() {
  const [items, setItems] = useState([
    {
      id: 1,
      name: 'Item 1',
    },
    {
      id: 2,
      name: 'Item 2',
    },
  ])

  const [selectedId,setSelectedId] = useState(null)

  return (
    <>
      {items.map((item) => (
        <Item key={item.id} id={item.id} name={item.name} handleClick={() => setSelectedId(item.id)} clicked={selectedId === item.id} />
      ))}
    </>
  )
}

export default App

Item.jsx

function Item({ id, name, clicked, handleClick }) {
  return (
    <button
      onClick={handleClick}
      style={{ color: clicked ? 'red' : 'blue' }}
      key={id}
    >
      {name}
    </button>
  )
}
  • Related