Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  19] [ 2]  / answers: 1 / hits: 30415  / 7 Years ago, wed, september 20, 2017, 12:00:00

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?


More From » reactjs

 Answers
11

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


[#56432] Sunday, September 17, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joep

Total Points: 32
Total Questions: 97
Total Answers: 104

Location: Wales
Member since Thu, Jul 1, 2021
3 Years ago
;