x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Pass props to functional component

    In React you will have component hierarchies which means one component will use another component inside it and you may need to pass properties from one component to another. This can be achieved using props object. In this example we will show how to pass props to from one component to another component.

    Step 1) Create a react application

    Create a react application using npx create-react-app passprops command.

    Step 2) Create Ball Component

    The Ball component will display the ball name & its color. It will receive an array of balls object using props which consist of two properties name & color.

    function Ball(props) {    console.log(props);    return (      <div className="App">        <p>This is a {props.balls[0].name}, and its color is {props.balls[0].color}</p>        <p>This is a {props.balls[1].name}, and its color is {props.balls[1].color}</p>      </div>    );}export default Ball; 

    Step 3) Update App.js

    import Ball from './Ball';const balls = [{name:'Football', color:'blue'}, {name:'Cricket Ball', color:'red'}]function App() {  return (    <Ball balls={balls}/>  );}export default App; 

    If you run npm start, you will see below on broswer

    This is a Football, and its color is blue

    This is a Cricket Ball, and its color is red

    Passing props to a low level component

    If you want to pass the props further to a low level component you can pass the props as shown below.

    Create Label Component

    function Label(props) {    console.log(props);  return (    <div>      <p>This is a {props.name}, and its color is {props.color}</p>    </div>  );}export default Label;

    Update Ball Component & use Label component

    Instead of reading each array, we will map props so that we dont need to read props using array index.

    import Label from './Label';function Ball(props) {  console.log(props);  return (    <div>      {props.balls.map((ball) => (        <Label name={ball.name} color={ball.color}        />      ))}    </div>  );}export default Ball;

    Comments

    Leave a Reply

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











    Share This