Hi. Welcome to another wonderful tutorial which is part of the React JS series. If you are new here, check out our previous articles and subscribe to our YouTube channel to get the video tutorial of our tutorials.
In this tutorial, we will discuss about React JS props, also known as properties. Props are like function arguments in JavaScript which are passed into React JS components. These props are written in same way as HTML attributes; that is, property-value pair.
Now let’s see how to add and use props in React JS. We will use a case where we want to print out welcome on the web page using a particular name which is to be passed as property.
We add the property when rendering the component by adding an attribute (which is a name in this case) which takes as value the name which we desire to display. We will name our component Hello and it will be written in the render.() function as seen below.
Now we have a name property associated with the Hello component. We can now display this property whenever we want using React JS props.
We will see how to display this name in the Component using both functional and class components.
Functional Component:
In the create-react-app boiler plate, we will create a new component file called Test.js and then modify the index.js file as seem below.
index.js
import React from 'react';
import ReactDOM from 'react-dom';import Hello from './Test'ReactDOM.render(, document.getElementById('root'));
Test.js
function Hello (props) {
returnHey, welcome {props.name}
;}export default Hello;
As you can see, with the functional component, you just need to pass the word props as param to the function and then call props.name where name is the attribute or property where ever u want to display its value.
Class Component:
With the class component, maintain the content of the index.js file and let your class component be as seen below.
import React from 'react';
class Hello extends React.Component {render() {returnHey, welcome {this.props.name}
;}}export default Hello;
The case of a class component is little bit different in the case that you get the property value using this keyword; this.props.name
Also notice the first line of code which cannot omitted if we are to use class component.
OUTPUT
Finally, we displayed the name that was passed as property.
Thanks.
See you in our next article.
Comments
Post a Comment
Please do not enter any spam link in the comment box.