Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clickable div acting as a button function react js

I have a button function inside the component 'CZButton', the button is used in "personlist" for a pop up, I am trying to make the div card inside of either 'personlist' or 'person' clickable so that instead of clicking the button, the div would be clicked and shows the drawer pop up.

I tried adding onclick inside divs and but it did not seem to reach the drawer function. here is a sandbox snippet, would appreciate the help.

https://codesandbox.io/s/l9mrzz8nvz?fontsize=14&moduleview=1

like image 986
Alpub Avatar asked Jan 01 '23 05:01

Alpub


2 Answers

You can add an onClick listener in React just by writing something like:

// omitting the rest of the render function for brevity
return (
    <div className="row" onClick={e => console.log("Clicked")}></div>
);

Just be careful with the HTML semantics. Although it is possible, I wouldn't really recommend adding onClick events to a div. There are good resources online about HTML5 standards and what you should adhere too.

like image 63
Dennis O'Keeffe Avatar answered Jan 05 '23 17:01

Dennis O'Keeffe


Live Demo: https://n329k226om.codesandbox.io/ Before Clicking Div After Clicking Div

App.js

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  constructor() {
    super();

    this.test = this.test.bind(this);
  }

  test() {
    alert("function executed on clicking div");
  }

  render() {
    return (
      <div>
        <div
          onClick={() => this.test()}
          className="interactivediv fa fa-window-close"
        >
          div
        </div>
      </div>
    );
  }
}

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

styles.css

.App {
  font-family: sans-serif;
  text-align: center;
}

.interactivediv {
  height: 150px;
  width: 150px;
  background: rgb(68, 196, 196);
  cursor: pointer;
   border: 1px solid grey;
}

.interactivediv:active {
  border: 2px solid black;
}
like image 28
Aftab22 Avatar answered Jan 05 '23 18:01

Aftab22