-1

React call onClick that call useState() in parent automate when call useState() in chide

I would like to close div but I cannot, its will always call onClick at parent in the final then it always "open"

import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const Message = () => {
  const [message, setMessage] = useState("");

  const click = () => {
    console.log("open");
    setMessage("open");
  };

  const close = () => {
    console.log("close");
    setMessage("close");
  };

  return (
    <div>
      <div onClick={() => click()}>
        {message === "open" ? (
          <div>
            open
            <button onClick={() => close()}>close na</button>
          </div>
        ) : (
          <div>not open</div>
        )}
      </div>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<Message />, rootElement);
Nappy
  • 3,016
  • 27
  • 39
Tudtude
  • 3
  • 2
  • 2
    Welcome to SO. The question is really hard to read and to make sense of because of the language. Maybe you could improve that. – Nappy Sep 02 '19 at 17:05
  • Are you seeing the console logs when you click? – Jared Smith Sep 02 '19 at 17:07
  • @Nappy -> I agree, my english has some problem anyway there is someone understand and solve it! backtick -> yes, it duplicate and I will not know in first time due with I don't know root of problem are come from stopPropagation JaredSmith -> yes, and see they are call parent oncliked but I don't know how to solve it – Tudtude Sep 03 '19 at 07:51

1 Answers1

0

You need to stop event bubbling. Modify your code as follows.


import React, { useState } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const Message = () => {
  const [message, setMessage] = useState("");

  const click = () => {
    console.log("open");
    setMessage("open");
  };

  const close = (e) => {
   e.stopPropagation(); // Stop this click event to trigger click on parent onClick()
    console.log("close");
    setMessage("close");
  };

  return (
    <div>
      <div onClick={() => click()}>
        {message === "open" ? (
          <div>
            open
            <button onClick={(e) => close(e)}>close na</button> // pass event or use onClick={close}
          </div>
        ) : (
          <div>not open</div>
        )}
      </div>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<Message />, rootElement);

For more info about bubbling and capturing, read Event bubbling and capturing.