Reputation: 1482
I searched around the internet for an answer to this question, and I didn't find one. Therefore I am posting my question here.
I have a parent component (App) and a child component (Child). The App component has a state with some data in it, like so:
class App extends Component {
constructor() {
super()
this.state = {
currentOrganization: {
name: 'name',
email: 'email'
}
}
render() {
return (
<Child data={this.state.currentOrganization} />
)
}
}
}
In my Child component, I have a form:
class Child extends Component {
constructor() {
super()
this.state = {
formData: {
name: '',
email: '',
}
}
}
render() {
return (
<Form ... />
)
}
}
According to the React docs, forms generally should have a state containing properties that correspond with each element of the form. The form that lies in my Child component must have the data of the currentOrganization (as seen in the App component) pre-populate into itself.
In order to accomplish this, I have to set the state of the Child to the props it receives from its parent.
What's the best way to check if my Child component received the props it needs in order to update its own state?
Upvotes: 17
Views: 31029
Reputation: 781
You can assign default props to component.
class Child extends Component {
constructor(props) {
super(props);
this.state = {
formData: {
name: props.name,
email: props.email,
}
}
}
render() {
return (
<Form ... />
)
}
}
Child.defaultProps = {
name: '',
email: '',
};
P.S.
props
is JS object so You can check property like this
"prop_name" in this.props // true|false
Upvotes: 25