Somethingwhatever
Somethingwhatever

Reputation: 1368

OnChange Handler ReactJS?

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.

Upvotes: 0

Views: 57

Answers (2)

SuccessFollower
SuccessFollower

Reputation: 220

You can use like this:

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

Upvotes: 0

Maheer Ali
Maheer Ali

Reputation: 36594

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,
  });
}

Upvotes: 3

Related Questions