0

My state looks like this

state = {
  basic: {
    entry: 'index.js',
    output: {
      path: 'dist',
      filename: 'bundle.js',
    }
  }
}

I have defined a callback for input onChange event :

handleUpdateString = (e) => {
  const name = e.target.name
  const value = e.target.value
  this.setState({ [name]: value })
  console.log(this.state)
}

say my input name is 'basic.entry'

my state is updated, but instead of having this.state.basic be { entry: 'some value'}

I end up with a new key in my state : { basic.entry: 'some value' }

I have tried using dot-object to convert the dot-seperated string to a nested object, and passing this to setState but the state appears to be unchanged.

What are simple solutions to this problem ?

1
  • Try this.setState({ name: value }); Commented Feb 19, 2017 at 19:02

2 Answers 2

0

Use a switch statement with explicit setState.

Sign up to request clarification or add additional context in comments.

Comments

0

This is not a React question but a pure JavaScript question on how to set a nested property on any object using a dot-notated string for the property. There is an answer here: Javascript object key value coding. Dynamically setting a nested value

Using that example in React:

handleUpdateString = (e) => {
  const name = e.target.name
  const value = e.target.value
  const state = Object.assign({}, this.state);
  setData(name, value, state);
  this.setState(state);
  console.log(this.state)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.