Contact Information

No. 1101, 24th Main, JP Nagar, 1st Phase, Bangalore 560 078

Understanding ReactJS Props

In this chapter, you will learn about ReactJS Props. The word props stands for properties. Props are immutable objects that are used to send data to the components. Props are read-only property values that are passed from the parent component to child component.

Let’s continue from where we left off in the last chapter. We have already created 2 functional components and 1 class component. Now let’s use props to send data to these components.

import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
    return (
<img src={logo} className="App-logo" alt="logo" />

Welcome to Tech diagonal tutorials

<FunctionalComponent name={"Adam"}/> <FunctionalComponentArrow course={"React"}/> <ClassComponentExample message={"Welcome"}/>
); } function FunctionalComponent(props){ return

Func Component Example {}

} const FunctionalComponentArrow = (props) => { return

Func Component Arrow Example {props.course}

} class ClassComponentExample extends React.Component { render() { return

Class Component {this.props.message}

; } } export default App;
Now let’s recap what happens in this example.
  • ReactDOM.render function is called with <FunctionalComponent name={“Adam”}/> , <FunctionalComponentArrow course={“React”}/> and <ClassComponentExample message={“Welcome”}/> components.
  • React call FunctionalComponent with name = “Adam”, FunctionalComponentArrow with course = “React” and ClassComponentExample with message = “Welcome”
  • You can access functional component props using
  • FunctionalComponent returns <h1>Func Component Example Adam</h1>
  • FunctionalComponentArrow returns <h1>Func Component Arrow Example React</h1>
  • ClassComponentExample returns <h1>Class Component Welcome</h1> element but you need to use this.props.message to access props.
  • React DOM updates the above elements returned from the components.

Default Props

Now you must be wondering what happens when parent component does not pass any attribute to child component. You can check that. Change ClassComponentExample declaration inside render as shown below

<ClassComponentExample />
As you can see, there is nothing in front of Class Component text since we are not passing any props.

You can set default property values for a component. If the parent component does not pass any values then component uses default prop values. You can declare default props as shown below.

ClassComponentExample.defaultProps = {
    message:"Default Msg"
Add this code above export default App statement. Now ClassComponentExample checks for message property value from the parent component if it is not available then values from defaultProps are used.

Chapter 3 - Understanding ReactJS Components

Chapter 5 - ReactJS Component State

Leave a Reply

Your email address will not be published. Required fields are marked *