BEDev
BEDev

Reputation: 739

How can I update my React component state?

I'm currently building out a contact form in React, and have a number of tags (interests) the user can select. I currently have a ContactForm and a Tag component, which is used when the data is mapped.

When the user clicks on a specific Tag, this should be added to the tags array if it's not already in the array, else if it already exists it should be removed from the array. This appears to work as required.

However, I also require the state of the Tag that's been clicked to be toggled between true/false. Given I already have an onClick for the Tag component, how can I pass down the state change to the Tag component?

import React, { FunctionComponent, useState } from 'react';

const Tag = ({ value, onClick, children }) => {
  const [isClicked, setIsClicked] = useState(false);

  return (
    <div key={key} onClick={onClick}>
      <span>{children || value}</span>
    </div>
  );
};

const Tags = [
  { key: '1', title: 'Tag 1' },
  { key: '2', title: 'Tag 2' },
  { key: '3', title: 'Tag 3' },
];

const ContactForm: FunctionComponent = () => {
  const [tags, setTags] = useState([]);

  const handleClick = (title) => {
    if(!tags.includes(title)) {
      setTags([...tags, title]);
    } 
    else {
      const updatedTags = tags.filter((el) => el !== title);
      setTags(updatedTags);
    }
  }
  return (
    <>
      {Tags.map(({ title }, index) => {
        return (
          <Tag key={index} onClick={() => handleClick(title)}>
            {title}
          </Tag>
        );
      })}
    </>
  );
};

export default ContactForm;

Upvotes: 0

Views: 65

Answers (2)

Vo Quoc Thang
Vo Quoc Thang

Reputation: 1396

Just provide your custom onClick in Tag component

const Tag = ({ value, onClick, children }) => {
  const [isClicked, setIsClicked] = useState(false);

  const handleClicked = () => {
     setIsClicked(prevState => !preState);
     onClick();
  }

  return (
    <div key={key} onClick={handleClicked}>
      <span>{children || value}</span>
    </div>
  );
};

Upvotes: 2

Durro
Durro

Reputation: 13

I'm a beginner but i think that you can change it's state by just typing an if right under the "const handleClick" function, you check if it's false then setIsClicked(true) else the opposite.

const handleClick = (title) => {

//code added - change isClicked state right when you click    
if(isClicked === false){
  setIsClicked(true)
} else {
  setIsClicked(false)
}

if(!tags.includes(title)) {
  setTags([...tags, title]);
} 
else {
  const updatedTags = tags.filter((el) => el !== title);
  setTags(updatedTags);
}

}

Upvotes: 0

Related Questions