Props in React js

props in react js


What are props?

Consider a function in any programming language. How do we pass values to the function? Using parameters. Props (properties) are similar to parameters. They are used to pass data from one component to another in React. Below is the simplest example on how to pass props:

Here in this example , we imported one <Student /> component in to <App /> component, but in App component we assigned some values, for Student components, this is called as Props... in Functional Component


    import React from 'react';
    import Student from './Student';

    function App() {
        return (
            <div>
                <Student name={"ramesh"} email={"ramesh@gmail.com"} />            
            </div>
        );
    }
    export default App;
   

Student Component


    import React from 'react';

    function Student(props) {
        return (
            <div>

                <h2>Student Name {props.name}</h2>
                <h2>Student EMail {props.email}</h2>

            </div>
        );
    }

    export default Student;
   

Here in this App component we assign variable values as a Props for Child Component

   
  const Banner = props => {
    const name = props.name
    return <div>Hello {name}</div>
  }

  function App() {
    return (
      <div>
        <Banner name="Abhishek" />
      </div>
    )
  }

  export default App

A couple of things you need to be aware of props are:

  1. Props are read-only, they should not be mutated.
  2. We cannot pass props from a child component to a parent component. Props always move from top to bottom in the component hierarchy.

Passing events with functions as Props

We can pass functions as props as well:



  const Banner = props => {
    const name = props.name
    return (
      <div>
        <p>Hello {name}</p>
        <button onClick={props.clickHandler}>Click Me</button>
      </div>
    )
  }

  function App() {
    const showAlert = () => {
      alert("Welcome!")
    }
    return (
      <div>
        <Banner name="Abhishek" clickHandler={showAlert} />
      </div>
    )
  }

  export default App


As you could see (line 17), the name of the function and the prop need not be the same.


Download::  Passing onClick event with Props  

Passing Boolean values

If you specify a prop without any values, it will be treated as a Boolean with value true:



  const Banner = props => {
    const name = props.name
    return <div>{props.show && <p>Hello {name}</p>}</div>
  }

  function App() {
    return (
      <div>
        <Banner name="Abhishek" show />
      </div>
    )
  }

  export default App

hi hi

If you need to pass false, then you need to explicitly mention it like:

<Banner name="Abhishek" show={false} />

Passing a state as a prop

You can pass the parent component state as a prop to the child component:



  import { useState } from "react"

  const Banner = props => {
    const name = props.name
    return (
      <div>
        <p>
          {props.greeting} {name}
        </p>
      </div>
    )
  }

  function App() {
    const [greeting, setGreeting] = useState("Hello")
    return (
      <div>
        <Banner name="Abhishek" greeting={greeting} />
      </div>
    )
  }

  export default App

Passing objects as Props

Consider the following example:

   
    const UserCard = props => {
    const name = props.user.name
    const role = props.user.role
    const age = props.user.age
    const profilePic = props.user.profilePic
    return (
      <div>
        <p>Name: {name}</p>
        <p>Role: {role}</p>
        <p>Age: {age}</p>
        <img src={profilePic} alt={name} />
      </div>
    )
  }

  function App() {
    const user = {
      name: "Abhishek",
      role: "Software Engineer",
      age: 27,
      profilePic: "image.jpg",
    }

    return (
      <div>
        <UserCard user={user} />
      </div>
    )
  }

  export default App

Default props

What if the parent component misses passing a prop? How to make sure our code does not break and there is always a fallback value? We can use default props for that.

Default props can be set using different ways.

Using Short circuit evaluation

We can use the logical OR operator to set a default name as shown below:


  const Banner = props => {
    const name = props.name || "user"
    return <div>Hello {name}</div>
  }

  function App() {
    return (
      <div>
        <Banner />
      </div>
    )
  }

  export default App


Using default parameters

We can also specify a default parameter while destructing the props:


  const Banner = ({ name = "user" }) => {
    return <div>Hello {name}</div>
  }

  function App() {
    return (
      <div>
        <Banner />
      </div>
    )
  }

  export default App


Fetching API Data..:

   
    import React from 'react';
    import {useState, useEffect} from 'react';

    function GithubUser ({name,location,avatar}){
        return(
            <div>
                <h1>{name}</h1>
                <p>{location}</p>
                <img src={avatar} height={"50px"} />
            </div>
       
        )
    }

    function App() {

        var [data, setData] = useState(null);
       
        useEffect(()=>{
            fetch(
                `https://api.github.com/users/moonhighway`
            ).then ((response)=>response.json())
            .then(setData);
        },[]);

        if(data)
        return(
            // <pre>
            //     {JSON.stringify(data,null,2)}
            // </pre>

            <GithubUser
            name={data.name}
            location={data.location}
            avatar={data.avatar_url}
            />
        );
        return (
            <div>
                <h2>Data</h2>
            </div>
        );
    }

    export default App;