Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
How can i apply style only to the clicked element [React]

I'm trying to apply conditional styles in React. I need to apply an animation when use click on delete button but this is applied to every element from the array

Component

import React, { useState } from 'react';

import './styles.css';

const Element = () => {
  const [onDelete, setOnDelete] = useState(false);
  const list = [
    {
      name: 'Jhon',
      age: '20',
    },
    {
      name: 'Maria',
      age: '25',
    },
  ];

  return (
    <>
      {list.map((item) => (
        <ul className={onDelete ? 'onDelete-apply' : ''}>
          <li>{item.name}</li>
          <li>{item.age}</li>
          <button onClick={() => setOnDelete(true)}>
            Delete
          </button>
        </ul>
      ))}
    </>
  );
};

export default Element;

Styles

.onDelete-apply {
  background-color: red;
}

*For example in this component i want to apply red background only to the clicked element *

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You should be traking the element that it is clicked by its index, insted of true or false, on click you set the index of the clicked item in the state and then check if that index is the same as the index of the element when rendered

import React, { useState } from 'react';

import './styles.css';

const Element = () => {
const [deletedIndex, setDeletedIndex] = useState(false);
      const list = [
        {
          name: 'Jhon',
          age: '20',
        },
        {
          name: 'Maria',
          age: '25',
        },
      ];
    
      return (
        <>
          {list.map((item, i) => (
            <ul key={i} className={deletedIndex === i ? 'onDelete-apply' : ''}>
              <li>{item.name}</li>
              <li>{item.age}</li>
              <button onClick={() => setDeletedIndex(i)}>Delete</button>
            </ul>
          ))}
        </>
      );
export default Element;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!