ditsikts ditsikts - 1 year ago 63
React JSX Question

React better way to get value

I have this react component and works fine!

var SettingsCtrl = React.createClass({
getInitialState: function() {
return {
value: 'select'
changeColor: function(){
this.setState({value: event.target.value});
if (document.getElementById('lang').value !== "select"){
document.body.style.backgroundColor = document.getElementById('lang').value
localStorage.setItem("color", document.getElementById('lang').value);

render: function () {
return (
<select id="lang" onChange={this.changeColor} value={this.state.value}>
<option value="select">Select</option>
<option value="lightblue">lightblue</option>
<option value="lightcoral">lightcoral</option>
<option value="lightgreen">lightgreen</option>
<SettingsCtrl />,

My question is if I can change the
with the state value somehow , I try this.state.value but doesnt work...

here is the gitlab repo

Answer Source

setState doesn't change state in sync way. So then you do:

this.setState({value: event.target.value});

you can't be sure what the state actualy already changed.

the better decision:

changeColor: function(event){      
    if(event.target.value !== 'select') {
        document.body.style.backgroundColor = event.target.value
        localStorage.setItem("color", event.target.value);

in this case you don't need state.value.