React Props complete guide for beginners

suchintan

SUCHINTAN DAS

Posted on June 25, 2022

React Props complete guide for beginners

Table of Content


📌 Introduction

📌 React Props

📌 Pro Tips

Reduce JSX Redundancy

Communicate between Parent and Child

Triangular communication between Parent and Components

📌 Thank you


Introduction

Hello amazing developer 🧑‍💻, before digging into this topic let me give you a small introduction and so instructions. Don't worry it would be quick and crisp.

I am Suchintan Das, a Full Stack Developer currently working over two startups. I have been into web development for past two years.

Connect me on 👉 Linkedin

The whole syntaxes and code are uploaded on this 👉 Repository . If you find it useful , you can star the repository to show a appreciation. Thanks !


React Props

I know most of you can't wait to know what's there on this amazing blog but let's just take a small breath understand a little bit about React Props

React Props

It's very similar to inheritance where some properties are passed from parent to child. Yes, in case of props also it's a one-way path.


Pro Tips


Reduce JSX Redundancy

Yes, you heard it write , you can actually send JSX to your child like any card body, section body or headings . Here's a small example of it.

Parent.jsx


import React from "react";
import Children from "./Children";
import "../../stylesheets/Part1/Parent.css"

const Parent = () => {
  const card = (title) => (
    <div className="card">
      <img
        src="https://i2.wp.com/sleepingshouldbeeasy.com/wp-content/uploads/2019/12/gross-motor-activities-for-1-year-olds-3.jpg"
        alt=""
      />
      <button>{title}</button>
    </div>
  );
  return (
    <>
      <div className="container">
        <h1>Showing childrens</h1>
        <br />
        <div className="cards">
        <Children childcard={card("Child")} />
        </div>
      </div>
    </>
  );
};

export default Parent;

Enter fullscreen mode Exit fullscreen mode

Children.jsx


import React from 'react'

const Children1 = (props) => {
  return (
    props.childcard
  )
}

export default Children1

Enter fullscreen mode Exit fullscreen mode

The card is defined in the parent component and it sent it to child component to use , which reduces the reductant code in the first place taking reusable components to another level.

Website Breakdown


Communicate between Parent and Child

I know most of the people while working over any website comes through a scenario where they want to get changes in parent based on changes on child component. Here's an example, let us take you are building a website with dark and light mode switching and you put the controller on the parent body and the child component section.

Communicate example

The idea here is using pointers !

Yes, you heard it right !

Structure

We know that the communication of props is a one-way process so after the props are sent there is no returning back of it even if there are some changes that occurred. To solve this issue we will send our states pointer to the child. Therefore any change in the value would mean change on the pointers address which would help use manipulate parent and child together. YES 😉!

Here's a small code peak -

Parent.jsx


import React, { useState } from "react";
import "../../stylesheets/Part2/Parent.css";
import Children from "./Children";

const Parent = () => {
  const [dark, setdark] = useState(false);

  const tooglemode = () => {
    dark ? setdark(false) : setdark(true);
  };

  const darkmode = (
    <i
      className={
        !dark
          ? "fa-solid fa-moon toogle-active"
          : "fa-solid fa-moon toogle-inactive"
      }
      onClick={tooglemode}
    />
  );

  const lightmode = (
    <i
      className={
        dark
          ? "fa-solid fa-sun toogle-active"
          : "fa-solid fa-sun toogle-inactive"
      }
      onClick={tooglemode}
    />
  );

  return (
    <div className={dark ? "application dark" : "application light"}>
      <div className="buttoncontroller">
        <h1>Website</h1>
        <div className="toogle">
          {darkmode}
          {lightmode}
        </div>
      </div>
      <Children dark tooglemode={tooglemode} />
    </div>
  );
};

export default Parent;

Enter fullscreen mode Exit fullscreen mode

Children.jsx


import React from "react";
import illustrator from "../../assets/images/illustrator.svg";

const Children = ({ dark, tooglemode }) => {
  return (
    <div className="section">
      <img src={illustrator} alt="" />
      <div className="sidebar">
        <h1>Welcome</h1>
        <p>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Cupiditate
          quod cum quibusdam rerum quis repellat consequuntur nesciunt deserunt.
          Voluptates aut eaque sed rerum dolorem alias quia! Quo magni hic odio
          exercitationem ratione.
        </p>
        {dark ? (
          <button
            onClick={tooglemode}
            className="light"
            style={{ border: "2px solid black" }}
          >
            Dark Mode
          </button>
        ) : (
          <button onClick={tooglemode} className="dark">
            Light Mode
          </button>
        )}
      </div>
    </div>
  );
};

export default Children;

Enter fullscreen mode Exit fullscreen mode

And a short demonstration of the same-

Communicate between Parent and Child


Triangular communication between Parent and Components

Triangular communication between Parent and Components

Yes I know that's something very exciting. Though the concept would remain same as earlier the only play here is that all the states that needs to be manipulated would be defined on the Parent Component and their pointers would be sent to all the childs. As a change is done on the pointer's address all the components would be accessing the data from the same address result being passed on all the 3 of them.

Let's have our peak on the code -

Parent.jsx


import React, { useState } from "react";
import "../../stylesheets/Part3/Parent.css";
import Children1 from "./Children1";
import Children2 from "./Children2";

const Parent = () => {
  const [show, setshow] = useState(true);
  const [count, setcount] = useState([1]);

  const toogle = () => {
    show ? setshow(false) : setshow(true);
  };

  const maintaincount = (event) => {
    event.target.id === "add"
      ? setcount([...count, count[count.length] + 1])
      : setcount(count.slice(0, -1));
  };

  return (
    <div className="application-container">
      <div className="header">
        <button onClick={maintaincount} id="add">
          Add
        </button>
        <button onClick={maintaincount} id="delete">
          Delete
        </button>
      </div>
      <div className="section-application">
        <Children1 show toogle={toogle} />
        <Children2 count={count} show />
      </div>
    </div>
  );
};

export default Parent;

Enter fullscreen mode Exit fullscreen mode

Children1.jsx


import React from 'react'

const Children1 = ({toogle}) => {

  return (
    <div className="section1">
        <h1>Control Text Visibility</h1>
        <button onClick={toogle}>Toggle</button>
    </div>
  )
}

export default Children1

Enter fullscreen mode Exit fullscreen mode

Children2.jsx


import React from "react";

const Children2 = (props) => {
  console.log(props.show);
  return (
    <div className="section2">
      {props.show ? (
        props.count.map((ele) => {
          return (
            <div className="section2-application" key={ele}>
              <h1>Sample Text</h1>
              <p>
                Lorem, ipsum dolor sit amet consectetur adipisicing elit. Iure,
                ratione necessitatibus officia asperiores quia quaerat
                aspernatur est dignissimos corrupti ullam qui sapiente dolorum
                aliquid!
              </p>
            </div>
          );
        })
      ) : (
        <div>Activate show to view the list</div>
      )}
    </div>
  );
};

export default Children2;

Enter fullscreen mode Exit fullscreen mode

Here's the website -

Website

And a short website breakdown to help you understand the same.

Website Breakdown

That's all for today. I hope it really helped you to learn new things.


Thank you

You have made it till the end of this blog 🤗. More such blogs are on the line .

It would be encouraging if a small comment would be there on the blog. I go through each one of them so do comment 😉.

If you want to get a notification 🔔 when it would be published , don't forget to tap on the follow button ☝.

And at last I want to say 👇

Keep coding #️⃣ , keep rocking 🚀

💖 💪 🙅 🚩
suchintan
SUCHINTAN DAS

Posted on June 25, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related