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 | State vs props
- EmberJS vs ReactJS
- ReactJS | Router
- ReactJS | forms
- ReactJS | Virtual DOM
- ReactJS | Using Babel
- ReactJS | Refs
- ReactJS | Fragments
- Difference between ReactJS and Vue.js
- ReactJS | Lists
- ReactJS | Keys
- ReactJS | Components
- ReactJS | Components - Set 2
- ReactJS | Introduction to JSX
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.