D
D
Denis_81062021-08-15 22:11:36
React
Denis_8106, 2021-08-15 22:11:36

How to add class active to active component?

Guys, tell me how to implement such a task in the functional style of React (+ hooks).
There is a parent component, it has 2 buttons and 2 tables. At the beginning (when the app is loaded), the 1st button and the 1st table have the active class. When you click on the 2nd button - the active class goes to the 2nd button and the 2nd table. Well, etc. , I think the functionality is clear. When a button is clicked, its style changes (add class active) + the corresponding table has an active class.

I implemented it quickly in JS, but there were difficulties in React. If necessary, you can also use the show class, if necessary. In general, I will be grateful for any help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
n1ksON, 2021-08-15
@Denis_8106

import React, { useState } from "react";

export default function App() {
  const [state, setState] = useState([
    { id: 0, status: true },
    { id: 1, status: false }
  ]);
  const chooseItem = (id) => {
    const newArr = state.map((item) =>
      item.id === id ? { ...item, status: true } : { ...item, status: false }
    );
    setState(newArr);
  };
  return (
    <div className="App">
      {state.map((item) => (
        <div style={{ border: item.status ? "3px solid tomato" : "none" }}>
          <div>TABLE {item.id}</div>
          <button onClick={() => chooseItem(item.id)}>CLICK</button>
        </div>
      ))}
    </div>
  );
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question