Home > other >  useState is not changing it's value
useState is not changing it's value

Time:08-31

I have tried to write a component to open a new window depending from the Boolean. I did a lot of components like that - that's why I totally don't understand why it doesn't work. It looks like "setShowWebsite" is not working correctly. Its changing it's value for true after click and rendering new component - however later I cannot do anything with that. I tried to put the "false" button on almost every dom element, but didn't work either. I checked with the console.log and the components are clicked, the eventListener is working correctly. Only the state is not changing for false.

setShowWebsite putting this into child component:

const Book: React.FC<{ name: string; author: string }> = ({ name, author }) => {

  const [showWebsite, setShowWebsite] = useState(false);

  useEffect(() => console.log(showWebsite), [showWebsite]);

  return (
    <BookWrapper onClick={() => setShowWebsite(true)}>
      {showWebsite ? <BookWebsite name={name} description={author} setShowWebsite={setShowWebsite} /> : undefined}
      <BookName>
        <h3>{name}</h3>
      </BookName>
      <BookAuthor>
        <h3>{author}</h3>
      </BookAuthor>
    </BookWrapper>
  );
};

Child component:

const BookWebsite: React.FC<Props> = ({ name, description, setShowWebsite }) => {

  const closeWebsite = () => {
    setShowWebsite(false);
    console.log('element was clicked');
  }

  return(
    <BookWindow>
      <IconWrapper onClick={() => closeWebsite()}>
        <i className="fa-solid fa-x"></i>
      </IconWrapper>
      <h1>{name}</h1>
      <p>{description}</p>
    </BookWindow>
  )
}

CodePudding user response:

It is because BookWrapper onClick and IconWrapper onClick working at the same time when you click on IconWrapper. You can use stopPropagation

const closeWebsite = (event) => {
  event.stopPropagation();
  setShowWebsite(false);
  console.log('element was clicked');
}


// ...

<IconWrapper onClick={closeWebsite}>

  • Related