Reputation: 173
I have a very simple form that takes in Name
and Age
. The Name
and Age
state are updated onChange
. However, once I'm done inputting name and age, at the very bottom, my p
tags do not return the name and age.
I believe my commonChange()
function is correct but unsure as to why the name and age is not shown once I input the data.
My code is the following:
import React from 'react';
import ReactDOM from 'react-dom';
import './normalize.css';
import './index.css';
class Form extends React.Component{
constructor(){
super();
this.state = {
nameValue: '',
ageValue: ''
}
this.commonChange = this.commonChange.bind(this);
}
commonChange(event){
this.setState(
{
[event.target.name]: event.target.value
});
}
render(){
return (
<div>
<h1>Name and Age Return</h1>
<form>
<label>Name:
<input type="text" name="nameValue" onChange={this.commonChange} />
</label><br />
<label>Age:
<input type="text" name="ageValue" onChange={this.commonChange} />
</label>
</form>
{this.props.nameValue && <p>{this.props.nameValue}</p>}
{this.props.ageValue && <p>{this.props.ageValue}</p>}
</div>
);
}
}
ReactDOM.render( < Form / > , document.getElementById('root'));
Upvotes: 0
Views: 178
Reputation: 6169
You need to replace this.props.nameValue
to this.state.nameValue
as you are getting value from state not props.
Upvotes: 0
Reputation: 34004
Both nameValue and ageValue are part of component state but not props.
Props is something you receive data from parent to the child component. State is something you manage with in the component.
So Change
{this.props.nameValue && <p>{this.props.nameValue}</p>}
{this.props.ageValue && <p>{this.props.ageValue}</p>}
To
{this.state.nameValue && <p>{this.state.nameValue}</p>}
{this.state.ageValue && <p>{this.state.ageValue}</p>}
Upvotes: 4