Home > Back-end >  How to add and delete the specific item from an array of an object in react.js?
How to add and delete the specific item from an array of an object in react.js?

Time:07-11

I am trying to add a functionality wherein when a user clicks on add channel button he can add the channel and it will show the newly added channel name in the respective teams. Similarly, when a user wants to delete a channel he can delete it so by clicking on delete button.

However, I figured out most of the code but seems like when am updating my newchannel list using useState it is showing me the error saying teams.channels.map is undefined and can not read properties.

If anyone can help on this would really be helpful and appreciated.

Please find the source code link below

Codesandbox link

CodePudding user response:

You should create a InputAddChannel component

const InputAddChannel = ({ handleAddChannel }) => {
  const [inputChannelValue, setInputChannelValue] = useState("");
  const handlInputChange = (event) => {
    event.preventDefault();
    const newChannelName = event.target.value;
    setInputChannelValue(newChannelName);
  };
  return (
    <>
      <input
        placeholder="add channel"
        value={inputChannelValue}
        onChange={handlInputChange}
      />
      <button
        disabled={!inputChannelValue}
        onClick={() => handleAddChannel(inputChannelValue)}
      >
        Add channel
      </button>
    </>
  );
};

and pass handleAddChannel function to it

const App = () => {
  const [newchannel, setNewChannel] = useState(teams);
  const [addteam, setAddteam] = useState("");

  const handleAddChannel = (team, i) => {
    const newData = newchannel.map((channel, index) => {
      if (i === index)
        return {
          ...channel,
          channels: [
            ...channel.channels,
            {
              channelName: team,
              channelid:
                channel.channels[channel.channels.length - 1]?.channelid   1 ||
                1
            }
          ]
        };
      return channel;
    });
    setNewChannel(newData);
  };

  const handleDeleteChannel = (cid, teamid) => {
    const newData = newchannel.map((channel, index) => {
      if (index === teamid)
        return {
          ...channel,
          channels: channel.channels.filter((c, i) => i !== cid)
        };
      return channel;
    });
    setNewChannel(newData);
  };

  const handleAddteam = (event) => {
    event.preventDefault();
    const addteaminput = event.target.value;
    setAddteam(addteaminput);
  };

  const handlSubmitAddteam = () => {
    const newaddedteam = newchannel.concat({
      name: addteam,
      channels: [
        {
          channelid: newchannel.length   1,
          channelName: "new"
        }
      ]
    });
    setNewChannel(newaddedteam);
  };
  return (
    <>
      <div className="App">
        {newchannel &&
          newchannel.map((team, i) => (
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                gap: "0.5rem",
                alignContent: "center",
                justifyContent: "center",
                border: "1px solid black",
                padding: "0.5rem"
              }}
              key={i}
            >
              <h1> {team.name} </h1>
              <InputAddChannel
                handleAddChannel={(value) => handleAddChannel(value, i)}
              />

              <div>
                {team.channels.map((c, cid) => (
                  <div
                    style={{
                      display: "flex",
                      gap: "1rem",
                      alignItems: "center",
                      justifyContent: "center",
                      border: "1px solid lightgray"
                    }}
                    key={cid}
                  >
                    <h6> {c.channelName}</h6>
                    <button
                      style={{ width: "5rem", height: "2rem" }}
                      onClick={() => handleDeleteChannel(cid, i)}
                    >
                      Delete
                    </button>
                  </div>
                ))}
              </div>
            </div>
          ))}

        <input
          placeholder="add team"
          value={addteam}
          onChange={handleAddteam}
        />
        <button disabled={!addteam} onClick={handlSubmitAddteam}>
          Add team
        </button>
      </div>
    </>
  );
};

You can check in my codesandbox. Hope it help!

  • Related