0

I have a component which i am importing into my App.js file and trying to set the value and an onChange method which i am passing down as props but not sure why that isn't working. Here is what the structure looks like:-

This is my app.js file:-

import React, { Component } from 'react';
import './App.css';
import Nested from './Nested.js'

class App extends Component {
   state = {
     childState: {
        title: 'New Title',
    }
 }

updateTitle = (e) => {
   const rows = [...this.state.childState];
   rows.title = e.target.value
     this.setState({
       rows,
  });
}


render() {
   return (
     <div className="App">
      <Nested
       title = { this.state.childState.title }
       updateTitle = {this.updateTitle.bind(this) } />
    </div>
   );
 }
}

export default App;

And this is my Nested Component:-

import React from 'react'

const Nested = (props) => {
    return (
       <div>
          <input value = { props.title } onChange = { props.updateTitle }></input>
      </div>
    )
 }

export default Nested;

If someone can point out what i am doing wrong in the above updateTitle, i'll appreciate it. Thank you.

5
  • What should be in place of that instead? Commented Feb 27, 2020 at 6:21
  • Can you please clarify what is purpose of rows and where you are using this? Commented Feb 27, 2020 at 6:23
  • It's just a const that stores a copy of the state so the state is never mutated directly. Commented Feb 27, 2020 at 6:24
  • updateTitle = (e) => { const rows = this.state.childState; rows.title = e.target.value this.setState({ childState: rows }); } Commented Feb 27, 2020 at 6:26
  • @aleemmd You should never mutate state directly. Here you are mutating rows which points to childState. See my answer Commented Feb 27, 2020 at 6:28

2 Answers 2

3

First mistake you making is that this.state.childState is an object and you spreading it inside []. You should use {}

Secondly you don't need to set rows as property in your state. You should use the same name which is childState instead of rows

updateTitle = (e) => {
   const childState = {...this.state.childState};
   childState.title = e.target.value
     this.setState({
       childState,
  });
}
Sign up to request clarification or add additional context in comments.

1 Comment

ohh i see now. thank you for the help. Accepting this as an answer.
0

You can use like this:

updateTitle = (e) => {
  this.setState(prevState => ({
    ...prevState,
    childState: {
      title: e.target.value,
    },
  }));
}

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.