xoomer xoomer - 11 months ago 68
Javascript Question

ReactJs onClick add className

I am new to reactjs.

So I have an issue. My className does not update when I trigger the onClick event. What might be cousing the problem?

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

export default class Categorie extends React.Component {
constructor() {
this.state = {categorie: "oldClass"};

addClassName() {
this.setState = ({categorie: "newClass"});

render() {
<div className={this.state.categorie} onClick={this.addClassName.bind(this)}>
<div className="categorieImgBlock">
<img className="categorieImg" src={this.props.img}/>
<span className="categorieName">{this.props.name}</span>
<span className="categorieCount">( {this.props.count} )</span>


Seems like a minor typo:

this.setState = ({categorie: "newClass"});

Shoud be:

this.setState({categorie: "newClass"});

Also setState() is asynchronous so your console.log statement right after it might not show you the actual new state, if you really want to do something after new state is set you should give it a callback function as 2nd argument.

this.setState({categorie: "newClass"}, () => console.log(this.state.categorie));