Karol Karol - 22 days ago 7
Javascript Question

Reactjs, something is wrong in my script but I don't know what

I'm working in react and I have here icon and I need to make this icon a hover state, like in css but I need to do this in react app, Here is my code:

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

var FontIcon = React.createClass({

getInitialState: () => {
return {
hover: false,
};
},

render(){

var _props = this.props,
iconStyle = {
'font-size': _props.size,
cursor: "default"
}

function hoverOn(){
this.setState({
hover: true
});
}

function hoverOff(){
this.setState({
hover: false
});
}

if (this.state.hover) {
iconStyle.color = _props.hoverColor;
} else {
iconStyle.color = _props.color;
}

return(
<i className="material-icons" style={iconStyle} onmouseenter={this.hoverOn} onmouseleave={this.hoverOff} >{_props.className}</i>
);
}
});

ReactDOM.render(
<FontIcon className="account_circle" size="100" color="blue" hoverColor="red" />,
document.getElementById('app')
);


And I don't know what is wrong :/ Thanks for help

Answer

First, do not use setState in render() !
After, beware that React events are all written in CamelCase because this is just javascript. Try something like this:

var FontIcon = React.createClass({

    getInitialState() {
        return {
            hover: false,
        };
    },
    hoverOff() {
        this.setState({
            hover: false
        });
    },
    hoverOn() {
        this.setState({
            hover: true
        });
    },
    render() {
        var _props = this.props;
        var iconStyle = {
            'font-size': _props.size,
            cursor: "default"
        };

        if (this.state.hover) {
            iconStyle.color = _props.hoverColor;
        } else {
            iconStyle.color = _props.color;
        }

        return(
            <i className="material-icons" 
               style={iconStyle} 
               onMouseEnter={this.hoverOn} 
               onMouseLeave={this.hoverOff} >
                {_props.className}
            </i>
        );
    }
});