Home > other >  React useState conditional initial value
React useState conditional initial value

Time:02-17

What i'm trying to do is:

When you click the button, the initial value should be removed from the array list and replaced with the component value.

On the other hand, the array list shouldn't be empty at any time. If you remove your components from the list one by one (by selecting them when they are already picked), the initial value should reappear as soon as all your components are gone.

Here is my code:

import "./box.css";
import React from "react";

export default function Box({ name, age, id, adder }) {
  return (
    <div className="container">
      <p>ID: {id}</p>
      <p>Name: {name}</p>
      <p>Age : {age}</p>
      <button
        onClick={() => {
          adder(name, age);
        }}
      >
        click me
      </button>
    </div>
  );
}

Edit Invisible Backdrop

CodePudding user response:

hey so i made a few simple changes in your app.js =>

import "./App.css";
import { data } from "./Data";
import { useState } from "react";
import React from "react";

import Box from "./components/box";
function App() {
  const [list, setList] = useState([]);
  const adder = (name, age) => {
    if (list.some((item) => item.name === name)) {
      setList(list.filter((item) => item.name !== name));
    } else {
      setList([...list, { name: name, age: age }]);
    }
  };
  console.log(list);
  return (
    <div className="App">
      {data.map((el) => {
        return <Box key={el.id} {...el} adder={adder} list={list} />;
      })}
      <h3>
        ArrayList :
        {list.length >= 1? list.map((el) => {
         return `[${el.name} ${el.age}], `;
        }):'unknown unknown'}
      </h3>
    </div>
  );
}

export default App;

what i did is removing initial object from list(leaving it empty[]) and then ask if there is items in the list and if not i display unknown as you wanted.

  • Related