ReactJS Props - React Tutorial


React Props


We have already learnt that how to render react component into html div container by using reactDOm method in index.jsx. In previous lesson, we created react component App.jsx and render it in index.jsx without passing any jsx attribute to App component as below:-

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
var root = document.getElementById('root');
ReactDOM.render(<App />,root);

However, we can pass jsx attributes to react component. These passing jsx attributes to react component are called props.

Props are the arguments passed to react component via jsx attribute. All jsx attributes becomes object before passing.

In javascript, we pass arguments to function. Similarly, props are the jsx attributes passed to the react component.

Today, we create react component Student.jsx using function as well as class that get props as input.

Steps to use props
  • Create Student.jsx in src folder
  • Import react library
import React from 'react';

  • First we write a function component "Student" (We write arrow function) that uses props to set student name and roll number in html elements and return as below
const Student = (props=> {
    return(
        <div>
            <h1>Student Name : {props.name}</h1>
            <h2>Roll Number: {props.rollNo}</h2>
        </div>
    );
}
export default Student;

Props is an object so get name and rollNo of this object using dot (.) operator and set html element in curly braces.
  • OR we can write a class component "Student". Inside class, we can get props object using "this" operator and set html element as below
class Student extends Component{
    render(){
        return(
            <div>
                <h1>Name:{this.props.name}</h1>
                <h2>Roll No:{this.props.rollNo}</h2>
            </div>
        );
    }
}
export default Student;

Props are read-only and can only be used. No component (function, class) is allowed to change props. 

You can write reactjs default props for Student component before export as

Student.defaultProps = {
    name: 'Liam',
    rollNo: '3432'
}

  • Import Student component in index.jsx
import Student from './Student';

  • Render Student component in div container by passing name and rollNo attributes as props
var root = document.getElementById('root');
ReactDOM.render(<Student 
name='Johson' 
rollNo='12345' />,root);

  • Start development server (command: npm start) and view output in browser.

No comments:

Post a Comment