Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Check If Props Exist

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?

like image 336
lsimonetti Avatar asked Sep 20 '17 19:09

lsimonetti


People also ask

How do you check if component is rendered React?

Using React DevTools to highlight what components rerendered To enable it, go to "Profiler" >> click the "Cog wheel" on the right side of the top bar >> "General" tab >> Check the "Highlight updates when components render." checkbox.

How props are passed in React?

Props are arguments passed into React components. Props are passed to components via HTML attributes. props stands for properties.


1 Answers

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

like image 175
Rafael Hovsepyan Avatar answered Sep 18 '22 05:09

Rafael Hovsepyan