Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

How to pass data to a component in React JS

How to pass data to a component in React JS

In this chapter, you will learn how to pass data to a component in React JS. In the last chapter, we have created our custom component for the employee, now its time to pass dynamic data to the employee component. Let us understand how to display the dynamic data in the component. It’s very important to understand what is props in the React JS in order to pass data to the component.

What is props in React JS?

  1. Props is an object and hold all the attributes that we pass to the component
  2. Props short for properties mean attributes of a component.
  3. You can add n number of attributes to your component as you wish
  4. You can access the same properties in the component
  5. You can use single curly braces to access it

Let’s see the below example to how to pass props to the component. Follow the below steps

Step 1:
Create the file src/Employee/Employee.js if you have it already paste the below code snippet

import React from 'react';

const employee = (props) => {
return <p>Hi I am {props.name} and my employee ID: {props.empId}</p>
}

export default employee;

Steps 2:
Create the file src/App.js if you have it already paste the below code snippet

import React, {Component} from 'react';
import './App.css';
import Employee from './Employee/Employee'
class App extends Component {
  render() {
    return (
      <div className="App">
        <h1>Welcome to react JS tutorial</h1>
        <Employee name='Stark' empId='123'/>
        <Employee name='Mickel' empId='124'/>
        <Employee name='John' empId='125'/>
      </div>
    );
  }
}

export default App;

Now look at the URL: http://localhost:3000/
You should be able to see the output

How to pass data to a component in React JS

2 thoughts on “How to pass data to a component in React JS

Comments are closed.