Search code examples
material-uiuuiduse-state

how to push an object with key using spreador to a new array


I want to add one element to the new array but the bug notification confused me and not work.If user click the color pickerinput and inputtitle and click the Add Colorbutton,one new card will show on the case.This is my expectation.

import ColorCards from "./ColorCards";
import React, { useState } from "react";
import data from "./initialState.json";
import { v4 as uuidv4 } from "uuid";

export default function CardsafterEvents({ title, color }) {
  const [colors, setColors] = useState(data.colors);
  const onRemove = (id) => {
    const newcolors = colors.filter((color) => color.id !== id);

    setColors(newcolors);
  };
  const AddColor = (id, title, color, timestamp) => {
    const newcolors = [
      ...colors,
      {
        id: uuidv4(),
        title: title,
        color: color,
        timestamp: new Date()
      }
    ];
    setColors(newcolors);
  };

  return (
    <>
      <ColorCards
        dataColors={colors}
        handleDelete={onRemove}
        title={title}
        color={color}
        HandleColor={AddColor}
      />
    </>
  );
}

full project link:https://codesandbox.io/s/material-demo-forked-62eh0?file=/CardsafterEvents.js:0-839


Solution

  • Your project has a few problems but, I got the features your requesting to work.

    See this updated Codesandbox.

    Edit Material demo (forked)

    The problem is the function HandleColor and how your dealing with state.

    I'll highlight the changes i made

    //Added to ColorCards.js
    const [title, setTitle] = useState("");
    const [color, setColor] = useState("");
    
    const handleColorChange = (e) => {
      HandleColor(title, color, new Date().toString());
    };
    
    //Slight modifications here
    <input
        type="text"
        placeholder="color title "
        style={{ width: "1500px", height: "20px", fontSize: "20" }}
        value={title}
        onChange={(e) => setTitle(e.target.value)}
    />
    <input
        type="color"
        value={color}
        onChange={(e) => setColor(e.target.value)}
        style={{ width: "50px", height: "30px" }}
    />
    <Button
        variant="contained"
        color="inherit"
        style={{ float: "right", width: "90px", height: "30px" }}
        onClick={handleColorChange}
    >
    
    
    //Changes in CardsafterEvents.js
    const AddColor = (title, color, timestamp) => {
        const newcolors = [
          ...colors,
          {
            id: uuidv4(),
            title: title,
            color: color,
            timestamp: timestamp
          }
        ];
        setColors(newcolors);
    };