JSColor onChange Event saying function is not defined

Viewed 163

I'm trying to use the onChange event for JSColor to call a function but every time it fires, I get an error stating that the function is not defined. My code is below.

export class NavBar extends React.Component {

    constructor(props) {
        super(props);
    }

    setLinkTextColor(color)  {
        console.log("hello")
    }

    render() {
        return (
            <div className="sideOptionContainer">
                <button className="jscolor" id="jscolor1" data-jscolor="{valueElement:'#val3', onChange: 'setLinkTextColor(this)'}">,</button>
                <input id="val3" value="rgba(255,160,0)" name="color3" type="hidden"/>
            </div>
        )
    }
}

I've tried moving the function inside of render() as function setLinkTextColor(color), thinking that maybe it had something to do with the scope, but I get the same exact error.

Edit: I've tried the following fix, removing the string from onChange and creating a global function -

export class NavBar extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div className="sideOptionContainer">
                <button className="jscolor" id="jscolor1" data-jscolor="{valueElement:'#val3', onChange: setLinkTextColor(this)}">,</button>
                <input id="val3" value="rgba(255,160,0)" name="color3" type="hidden"/>
            </div>
        )
    }
}

function setLinkTextColor(color)  {
    console.log("hello")
}

Although I'm not getting any errors anymore, the onChange event is no longer firing when I change the color input.

1 Answers

Since this is React, you need to bind your setLinkTextColor function in the constructor:

constructor(props) {
    super(props);
    
    this.setLinkTextColor = this.setLinkTextColor.bind(this);
}

Then, in your JSColor config, you can't use a string, because JSColor can't access your function inside of your class. Instead, do this:

render() {
    const jsColorConfig = {
        valueElement: '#val3', 
        onChange: this.setLinkTextColor
    };

    return (
        <div className="sideOptionContainer">
            <button className="jscolor" id="jscolor1" data-jscolor={jsColorConfig}>,</button>
            <input id="val3" value="rgba(255,160,0)" name="color3" type="hidden"/>
        </div>
    )
}
Related