Search code examples
reactjsevents

Display none in child element when clicking button - React


How can I, when clicking on the button, display none in the Test components.

function Teste({testeA,testeB}) {

    return <div> {testeA} - {testeB} </div> 
}

export default function Simulacao() {
 
    return <>
            <button onClick=""/>
            <Teste testeA="aaa" testeB="bbb"/>
            <Teste testeA="ccc" testeB="ddd"/>
        </>
}

I understand the concept of building components in React and reusing them, but I'm having difficulty working with events.


Solution

  • You can to do as below if you want to use CSS to hide them. You could also return <></> if show is false:

    import { useState } from "react";
    
    function Teste({ testeA, testeB, show = true }) {
      return (
        <div style={{ display: show ? "block" : "none" }}>
          {testeA} - {testeB}
        </div>
      );
    }
    
    export default function Simulacao() {
      const [showTeste, setShowTeste] = useState(true);
      return (
        <>
          <button
            onClick={() => {
              setShowTeste((showTeste) => !showTeste);
            }}
          >
            Toggle
          </button>
          <Teste testeA="aaa" testeB="bbb" show={showTeste} />
        </>
      );
    }