React js

How to use Props in React?

If you are new to React, you must have noticed the term props all across the tutorials and the code snippets that you come across. So what exactly are _props _and how do you use them correctly?
Props is short for Properties. In React, propscan be passed to a component, and they should not be changed within a component.
Props _cannot be changed within a component. _Props are immutable.
Keep in mind that in React, the data flow is unidirectional from parent to the child. Irrespective of whether you declare your component as a _class _or a _function, _the _props _should not be modified.

Conversation Between Components

Let’s visualize a conversation between the components in React to see if we can get some clarity around props.

Parent Component 1: “Hey there child component, I have some props that I want to send your way! You can use them to render, and you can pass them on to your children too! Remember you cannot change the props that I send you.”

Child Component 1: “Thanks for sending the props my way. I am going to render myself and will use the props that you sent me without changing them. I am going to send the props to my child as well.”

Child Component 2: “Hey thanks for sending me the props that I need, I am going to use that to render myself.”

Alright, you get the idea. The data flows unidirectionally and the props _are passed down the chain, but none of the children can modify the _props.
Now you may ask me, what if I wanted to modify the properties within my component? For that purpose you can use the state _in React. _State works differently. _State _in React is internal to a component and can be modified within the component. We will learn about _state _in depth in another blog post.

Passing Props

export default class Heading extends React.Component {
  render() {
    return (
      <div>
        <p>{this.props.message}</p>
      </div>
    );
  }
}
Heading.propTypes = {
  message: PropTypes.string.isRequired
};
In this example above, we have defined an ES6 class which is the Heading component. This component renders a message. Observe here, that the message is given to the Heading_component as a _prop.
Now the Heading_component can be rendered within any page or component with different messages. The point of using _prop _here is to reuse the code. Hence, the same _Heading_component can be used across the web app, with different _message _text passed each time as _props.

The caller

export default class PageOne extends React.Component {
  render() {
    return (
      <div>
        <Heading message={"Custom Heading for Screen One"} />
      </div>
    );
  }
}
This is an example of how the Heading _component can be called with _props. In this example, the message is sent to the _Heading _component as a _prop _from the _PageOne _component.
*Note: *Keep in mind, that within the Heading _component, the _message __prop cannot be changed. It is used only for rendering purposes and cannot be changed.

Okay, I get it but what are PropTypes?

React supports data validation through PropTypes. It is React’s in-built type-checker.
You can define components without PropTypes. But, without _PropTypes _or some form of type checking, we run into the risk of passing in a wrong data type to a component, which could cause a crash or some unexpected outcome in your application.
Now, let’s take a look at our Heading _component from the previous example, and add _PropTypes to it. We already had a _PropType _for the _message prop, _and we can add on to it.
import PropTypes from 'prop-types'

export default class Heading extends React.Component {

  render() {
    // ....
  }
}

Heading.propTypes = {
  message: PropTypes.string.isRequired,
  content: PropTypes.array.isRequired,
  onPress: PropTypes.func.isRequired,
  size: PropTypes.number.isRequired,
  styles: PropTypes.object.isRequired,
  isReady: PropTypes.bool.isRequired
}
As you can see from the example above, there are different types of _PropTypes _that we can add to our component. Strings, array, function, number, bool and so on.

What is isRequired and when do I use it?

As the name suggests, isRequired _tells React that the particular _prop _is required by the component. Anytime the component is called it needs to be passed the _props _that are marked as _isRequired. This ensures that we don’t accidentally miss certain _props _while calling components.
When we forget to pass the required props _to a component, React throws an error in the development console.This helps in catching missing _props during development phase.

What are defaultProps ?

Default values can be assigned to the props using defaultProps. When a component does not receive it’s _props_, then it resorts to the _defaultProps _that has been assigned.
Take a look further at the code snippet below that shows how we have added _defaultProps _to our _Heading _component.
// Default values for props
Heading.defaultProps = {
  message: 'Sample Default Text',
  content: [],
  size: 0,
  onPress: () => {},
  isReady: false
} 
It is not necessary to assign defaultProps if you have marked your props as required. You can use either one to be safe.
Always define explicit defaultProps for all optional props.
It is interesting to note that the type-checking using PropTypes happens after the defaultProps are assigned. So it type checks the default values assigned to the props as well. This is great!

Recap

  • _props _are short for properties.
  • _props _are immutable.
  • Data flow in React is unidirectional
  • _props _encourage code reuse.
  • React offers inbuilt type checking usingPropTypes.
  • isRequired is useds to mark props as required.
  • Define explicit defaultProps for all optional props.

Comments

Popular posts from this blog

'composer' is not recognized as an internal or external command in windows server

lEARN :: SQL | Views