Props in ReactJS

In the previous article, Components in ReactJS, we learned how to create components and to nest them in other components. In this we can say App component is the parent component and Comments is the child component.

  • PROPS is a way of passing data from parent component to child component.
  • This way we can customize or configure the child component, displaying different data in different child component or can react to an event.
  • A child component cannot pass data back to the parent component DIRECTLY. There are ways to pass data indirectly.
  • There is no limit to the amount of information that we can share through props.
  • Props is a short form of Properties.

Let’s continue with the Components article.

In the below code, we have created three properties: user, time, commentData.

index.js

This file has the parent component and props are passed from parent component to child component. Hence we are creating the props in index.js and will pass them to Comments.js which has the child component.
Below is the code

import React from 'react';
import ReactDOM from 'react-dom';
import { Comment } from 'semantic-ui-react';
import Comments from './Comments';

const App = function () {
    return (
        <Comment.Group>
            <Comments user="Apoorv" time="May" commentData="Comment1" />
            <Comments user="Akanksha" time="Yesterday" commentData="Comment2" />
            <Comments user="Aarav" time="Today" commentData="Comment3" />
        </Comment.Group>
    );
};

ReactDOM.render(<App />, document.getElementById('root'));
Comments.js

Below is the code

import React from 'react';
import { Comment } from 'semantic-ui-react';
import faker from 'faker';

const Comments = function (props) {
    return (
        <Comment>
            <Comment.Avatar src={faker.image.avatar()} />
            <Comment.Content>
                <Comment.Author as='a'>{props.user}</Comment.Author>
                <Comment.Metadata>                  
                    <div>{props.time}</div>
                </Comment.Metadata>
                <Comment.Text>{props.commentData}</Comment.Text>
                <Comment.Actions>
                    <Comment.Action>Reply</Comment.Action>
                </Comment.Actions>
            </Comment.Content>
        </Comment>
    );
}

export default Comments;
{props.commentData} this is how we use values of props in child component.

Below is the output of above code

Unknown's avatar

Author: Akanksha Gupta

I am a developer and working on SharePoint and Project Server in an MNC. I have more than 10 years of experience in the same field.

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started