How to use onClick with divs in React.js
Asked Answered
D

7

74

I'm making a very simple application where you can click on square divs to change their color from white to black. However, I'm having trouble. I'd like to use the onClick function to allow a user to click on a square to change its color, but it doesn't seem to be working. I've tried using spans and empty p tags, but that doesn't work either.

Here is the code in question:

var Box = React.createClass({
    getInitialState: function() {
        return {
            color: 'white'
        };
    },

    changeColor: function() {
        var newColor = this.state.color == 'white' ? 'black' : 'white';
        this.setState({
            color: newColor
        });
    },

    render: function() {
        return (
            <div>
                <div
                    style = {{background: this.state.color}}
                    onClick = {this.changeColor}
                >
                </div>
            </div>
        );
    }
});

Here's a link to my small project on CodePen. http://codepen.io/anfperez/pen/RorKge

Dauphin answered 10/11, 2016 at 19:23 Comment(1)
class components haven't been the recommended method for over 3 years, I would recommend you change this to a React Function Component. vars in general haven't been recommended for over 8 years, use const or let ``` lang-jsx const Box = () =>{ const [color, setColor] = useState('white') const changeColor = ()=> setColor(previousColor=>previousColor==='white' ? 'black' : 'white') return // the JSX ```Rossiter
S
78

To set your mind at ease, the onClick event does work with divs in react, so double-check your code syntax.

These are right:

<div onClick={doThis}>
<div onClick={() => doThis()}>

These are wrong:

<div onClick={doThis()}>
<div onClick={() => doThis}>

(and don't forget to close your tags... Watch for this:

<div onClick={doThis}

missing closing tag on the div)

Shaven answered 18/10, 2020 at 21:47 Comment(1)
From an accessibility perspective, it is right to add interactive events to non-interactive elements?Occam
I
48

This works

var Box = React.createClass({
    getInitialState: function() {
        return {
            color: 'white'
        };
    },

    changeColor: function() {
        var newColor = this.state.color == 'white' ? 'black' : 'white';
        this.setState({ color: newColor });
    },

    render: function() {
        return (
            <div>
                <div
                    className='box'
                    style={{background:this.state.color}}
                    onClick={this.changeColor}
                >
                    In here already
                </div>
            </div>
        );
    }
});

ReactDOM.render(<Box />, document.getElementById('div1'));
ReactDOM.render(<Box />, document.getElementById('div2'));
ReactDOM.render(<Box />, document.getElementById('div3'));

and in your css, delete the styles you have and put this

.box {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  float: left;
}

You have to style the actual div you are calling onClick on. Give the div a className and then style it. Also remember to remove this block where you are rendering App into the dom, App is not defined

ReactDOM.render(<App />,document.getElementById('root'));
Irrigation answered 10/11, 2016 at 20:11 Comment(1)
Thank you! It was styling the box that was tripping me up a bit. That definitely works!Dauphin
D
7

The Following code works now !!!

const test = () => {
const onClick = () => console.log('hi');

return (
<div onClick={onClick} aria-hidden="true">
  Content here
</div>
)};
Dotterel answered 24/6, 2021 at 1:11 Comment(0)
S
2

Your box doesn't have a size. If you set the width and height, it works just fine:

var Box = React.createClass({
    getInitialState: function() {
        return {
            color: 'black'
        };
    },

    changeColor: function() {
        var newColor = this.state.color == 'white' ? 'black' : 'white';
        this.setState({
            color: newColor
        });
    },

    render: function() {
        return (
            <div>
                <div
                    style = {{
                        background: this.state.color,
                        width: 100,
                        height: 100
                    }}
                    onClick = {this.changeColor}
                >
                </div>
            </div>
        );
    }
});

ReactDOM.render(
  <Box />,
  document.getElementById('box')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='box'></div>
Siemens answered 10/11, 2016 at 19:29 Comment(2)
Thanks Timo, but the code doesn't seem to work when I try to use it in my CodePen snippet. Is that because I also have a width and height specified in my CSS file? I edited it with your code, but it still doesn't work.Dauphin
How does it not work? The snippet in my answer works just fine.Siemens
R
1

Whilst this can be done with react, be aware that using onClicks with divs (instead of Buttons or Anchors, and others which already have behaviours for click events) is bad practice and should be avoided whenever it can be.

Rossiter answered 26/11, 2020 at 16:2 Comment(0)
M
0

This also works:

I just changed with this.state.color==='white'?'black':'white'.

You can also pick the color from drop-down values and update in place of 'black';

(CodePen)

Must answered 24/12, 2017 at 16:42 Comment(0)
S
-1

I just needed a simple testing button for react.js. Here is what I did and it worked.

function Testing(){
 var f=function testing(){
         console.log("Testing Mode activated");
         UserData.authenticated=true;
         UserData.userId='123';
       };
 console.log("Testing Mode");

 return (<div><button onClick={f}>testing</button></div>);
}
Syndicalism answered 14/6, 2017 at 8:36 Comment(1)
How this is related to the question ?Waechter

© 2022 - 2024 — McMap. All rights reserved.