Search code examples
cssreactjsinline-styles

Reactjs, inline style with state data


I have mapped an array of words to the button group. and in the state I have an index and a color value

this.state = {
            selectedWordIndex:'',  //e.g. 3
            selectedWordColor:''  //e.g. rgb(137,197,8)
        }

the index and the color are set in another function.

var counter = -1;
return this.state.sentenceArray.map((word) => {
        counter += 1
        return (
            <button
                key={counter}
                type="button"
                className="btn btn-default"
                style={{}}>{word}</button>);});

how can I change the color of the indexed button?


Solution

  • So if you want to change the color of button with the index === this.state. selectedWordIndex, following code should work.

    var counter = -1;
    return this.state.sentenceArray.map((word) => {
            counter += 1
            return (
                <button
                    key={counter}
                    type="button"
                    className="btn btn-default"
                    style={ this.state.selectedWordIndex === counter ? 
                            { color:this.state.selectedWordColor } : 
                            {}
                          }
                >{word}</button>);});