In our previous article ReactJS | Props – Set 1 we had discussed about props, passing and accessing props, passing props from one component to other etc. In this article, we will continue our discussion on props.
So, what if we want to pass some default information using props to our components. React allows us to do so. React provides us with something called defaultProps for this purpose. Let’s see about this in details:
The defaultProps is a method which we can use to store as much information as we want for a particular class. And this information can be accessed from anywhere inside of that particular class. Every piece of information you add inside the defaultProps, that will be added as the prop of that class. It might seem confusing at this point. Let’s look at a program where we will be using defaultProps to create some props for a class.
You can see in the above program we have created a default prop named title outside of the class ExampleClass and accessed this prop inside of that class using this.props statement.
We can also pass arrays as props, instead of passing single elements. Let’s just see how it is done in the below program:
In the above program, we have passed an array of names as a prop to the component ExampleClass. We have also accessed this array directly to print the content of the array. Below is the output when the above code is rendered:
You can see in the above program how we are iterating over the array passed to the component ExampleClass using map().
That’s all for this article. In our next article, we will see how to validate types in props or how to perform type-checking.
- ReactJS | Props - Set 1
- ReactJS | Methods as Props
- ReactJS | State vs props
- ReactJS | Keys
- ReactJS | Using Babel
- Difference between ReactJS and Vue.js
- ReactJS | Fragments
- ReactJS | Virtual DOM
- ReactJS | Refs
- ReactJS | AJAX and API
- ReactJS | Icons
- EmberJS vs ReactJS
- ReactJS | forms
- ReactJS | Router
- ReactJS | Lists
- ReactJS | Components
- ReactJS | ReactDOM
- ReactJS | Introduction to JSX
- ReactJS | Components - Set 2
- ReactJS | PropTypes