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

89
Views
Maping data in React and want toggle specific button

I can't toggle a particular button. I want to toggle that particular button in an array of buttons. Here is demo code link. Please correct it and share solved problem.

Code

import { useState } from 'react';
import { data } from './data';
import "./styles.css";

export default function App() {
  const [state, setState] = useState({
    toggle: true,
    index: ''
  })

  const onJoin = () => {
    setState({
      ...state,
      toggle: !state.toggle
    })
  }

  const onRequest = () => {
    setState({
      ...state,
      toggle: !state.toggle
    })
  }
  return (
    <div className="App">
      {data.map(data => {
        return(<div className='container'>
          <h1>{data.name}</h1>
          {state.toggle ?
          <button onClick={() => onJoin()}>Join</button>
          :
          <button onClick={() => onRequest()} >Request</button>
        }
        </div>)
      })}
    </div>
  );
}

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

0

Issue

You are using one state variable for all buttons. You need an array to keep track of which buttons are toggled

Solution

Instead of making toggle a boolean, make it a boolean array.

Working Codesandbox

Code

import { useState } from "react";
import { data } from "./data";
import "./styles.css";

export default function App() {
  const [state, setState] = useState({
    toggle: [],
    index: ""
  });

  const onJoin = (index) => {
    setState((state) => ({
      ...state,
      toggle: state.toggle.filter((t) => t !== index)
    }));
  };

  const onRequest = (index) => {
    setState((state) => ({
      ...state,
      toggle: [...state.toggle, index]
    }));
  };
  return (
    <div className="App">
      {data.map((d, index) => (
        <div key={index} className="container">
          <h1>{d.name}</h1>
          {state.toggle.includes(index) ? (
            <button onClick={() => onJoin(index)}>Join</button>
          ) : (
            <button onClick={() => onRequest(index)}>Request</button>
          )}
        </div>
      ))}
    </div>
  );
}

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!