Skip to content
Advertisement

Make onclick inside onclick in ReactJS

Hi guys I try to make onclick inside onclick, can I run clickdelete() without handleClick().

This is my code

                <div
                  className="row-queue"
                  key={index}
                  onClick={() => handleClick(item, index)}
                  style={
                    index === myvideoIndex ? playingcolor : playingcolor2
                  }
                >
                  <div className="column1-queue">{index + 1}</div>
                  <div className="column2-queue">{item.title}</div>
                  <div className="column3-queue">{item.singer}</div>
                  <div className="column4-queue">
                    <button
                      onClick={() => clickdelete(index)}
                      className="btn-delete"
                    >
                      <i className="fa fa-trash"></i>
                    </button>
                  </div>
                </div>

Hope you guys understand what I’m asking 😀

Advertisement

Answer

// Get a hook function

const {useState} = React
const Example = ({title}) => {
  const [count, setCount] = useState(0);

  return (
  <div>
    <div onClick={() => alert('parent')}>
    With => e.stopPropagation();
      <button onClick={(e) => {
      e.stopPropagation();
      alert('clicked button')
      }}>
        Click me
      </button>
    </div>
    
    <div onClick={() => alert('parent')}>
    Without =>  e.stopPropagation();
      <button onClick={(e) => {
     
      alert('clicked button')
      }}>
        Click me
      </button>
    </div>
      </div>
  );
};

// Render it
ReactDOM.render(
  <Example title="Example using Hooks:" />,
  document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>

yes it’s possible use event.stopPropagation() so that event will not propagate to our parent div click handler.

<button onClick={(e) => {
    e.stopPropagation()
    clickdelete(index)
}} className="btn-delete">
  <i className="fa fa-trash"></i>
</button>;
Advertisement