Home > OS >  Props are showing "undefined" when on click to send props to another component
Props are showing "undefined" when on click to send props to another component

Time:07-30

I am building a simple react app and I am beginner. I am trying to send state as props to another component But when I access props like this.props.name then it is showing undefined.

App.js

class Home extends React.Component {
    state = {
         fields : {
            name : '',
        }
    }

    updateField = evt => {
     const fields = Object.assign({}, this.state.fields);
    fields[evt.target.name] = evt.target.value;
    console.log(evt.target.value)
    this.setState({fields})
    }

    render() {
        return(
             <div>
                <form>
                  <input 
                     name="name" 
                     id="name_id" 
                     onChange={this.updateField} 
                     value={this.state.fields.name} 
                  />
                </form>
                <Link to='/second_component'><SecondComponent name={this.state.fields} />Submit</Link>
      <Routes>
        <Route path='/second_component' element={<SecondComponent/>} />
      </Routes>
             </div>
        )
    }
}

class SecondComponent extends React.Component {

   render() {
      return (
        <div style={{color: "white"}}>
          {console.log(this.props.name)}        
      </div>
      )
   }
}

export default Home;

I have tried many times but it is still not working. When I try to console.log then it is showing "undefined". Any help would be much Appreciated. Thank You in Advance

CodePudding user response:

Change fields[evt.target.name] = evt.target.value; to fields.name = evt.target.value; and name={this.state.fields} to name={this.state.fields.name}. Should work.

  • Related