DEV Community

Cover image for React Props complete guide for beginners
SUCHINTAN DAS
SUCHINTAN DAS

Posted on • Updated on

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 🚀

Top comments (15)

Collapse
 
peerreynders profile image
peerreynders • Edited

It's very similar to inheritance where some properties are passed from parent to child.

Inheritance is a is-a relationship. The relationship between a container and nested component is a has-a relationship.

Early React even described it as the owner-ownee relationship but community usage moved towards "parent-child" even though that makes absolutely no sense in reference to props.children.

function Avatar({username}) {
  return (
    <div>
      <ProfilePic username={username} />
      <ProfileLink username={username} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Old usage:

  • Owner: Avatar
  • Ownees: div, ProfilePic, ProfileLink
  • div is the parent to ProfilePic, ProfileLink
  • ProfilePic, ProfileLink are children to div

Community Usage:

  • Parent: Avatar
  • Child: div, ProfilePic, ProfileLink
  • div is the parent to ProfilePic, ProfileLink
  • ProfilePic, ProfileLink are children to div

Note how the community usage makes matters a lot more confusing.

  • Avatar is the Parent to div, ProfilePic, ProfileLink
  • ProfilePic, ProfileLink are passed via props.children to div

Two entirely different sets of parent-child relationships for everyone. And worse div has very little "parental control" over props.children short of ignoring them which is largely what happens in user components even though props.children is React's equivalent to WC's unnamed slot.

You use

<Children childcard={card("Child")} />
Enter fullscreen mode Exit fullscreen mode

What's wrong with using props.children instead:

<Children>
  <Card title="Child"/>
<Children/>
Enter fullscreen mode Exit fullscreen mode

which preserves the familiarity with markup better?


you can actually send HTML to your child like any card body

There is no actual HTML or even DOM involved; that is all react-dom's job'. JSX is a DSL for representing the React component tree where each component instance is responsible for rendering ReactNodes.

"JSX is an XML-like syntax extension to ECMAScript without any defined semantics."
JSX specification

JSX doesn't follow HTML formatting rules but stricter XML rules and is a JavaScript extension that in some framework specific way compiles to some JavaScript code that will eventually lead to some DOM elements being manipulated/created.

In the case of React the component tree is assembled; in the case of SolidJS actual DOM nodes are created to be included in the page's DOM - no HTML.

JSX's representation evokes the familiarity of markup—but it isn't markup.

Collapse
 
naveennamani profile image
naveennamani

I'm about to comment on that HTML part. JSX is just a representation of virtual DOM using HTML like syntax, however all the JavaScript code is generated by tools like Babel.

You can play around online Babel compiler and see for yourself how your JSX turns into js code which is what is handled by react.

https://babeljs.io/repl/#?browsers=defaults%2C%20not%20ie%2011%2C%20not%20ie_mob%2011&build=&builtIns=false&corejs=3.21&spec=false&loose=false&code_lz=DYUwLgBAHhC8A8ATAlgNwHwAsTGAewgHc8AnYReAehQyA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=env%2Creact%2Cstage-2&prettier=false&targets=&version=7.18.5&externalPlugins=&assumptions=%7B%7D

Collapse
 
suchintan profile image
SUCHINTAN DAS

Thanks naveennamani, for providing the link and the information.

Yes, I was also familiar with the fact that JSX is actually an extension provided by React to help us write the same code in HTML and in the backdoor it changes all the stuffs to JavaScript . Making the whole process less tiring for the developers .

But I avoided to dig that deep into the inner functionality while explaining the stuff so that any beginner can also easily grab the tip without striking their head over the whole backdoor mechanism.

Thread Thread
 
peerreynders profile image
peerreynders

React to help us write the same code in HTML

As another commenter already pointed out to you:

  • JSX represents React Components, not HTML.

Forget about the other details with regards to JSX. However referring to JSX as HTML is problematic especially in "teaching mode" as it perpetuates the wrong mental model.

JSX lets you declaratively compose React components. That's all there is to it.

Thread Thread
 
suchintan profile image
SUCHINTAN DAS

Peerreynders, I think you haven't read the whole sentence that I had written. I would request you to please read the whole thing as communication gap does create a lot of confusions.

In the whole line I said "JSX is actually an extension provided by React to help us write the same code in HTML and in the backdoor it changes all the stuffs to JavaScript" . I am not referring JSX as HTML, I pointed out the fact here that JSX is an extension that is provided by React to help developers write the same format of code as HTML into JavaScript with minimal changes.

Thread Thread
 
peerreynders profile image
peerreynders • Edited

I may understand what you mean but I'm convinced that your target audience is not going to come away with the same understanding.

write the same format of code as HTML

That phrasing alone is enough to establish a false equivalence between JSX and HTML. And to some degree it's only valid as long as you are talking about React's DOM element components. User components compose those DOM components. Container components may only compose User components without adding any additional DOM components. Providers have no equivalence in the DOM at all.

JSX is what makes React declarative. HTML happens to be declarative. JSX is XML. Both XML and HTML derived from SGML.

  • JSX composes React Components
  • HTML composes markup from HTML elements

The fact that a component's position in the component tree is linked to the position of the rendered content in the DOM tree is a leaky abstraction.


React's entire premise is to reuse React components in React Native. React Native is all components and JSX; no HTML, no DOM;

Thread Thread
 
suchintan profile image
SUCHINTAN DAS

Thanks peerreynders for the feedback. Yes, there a case that people take away a wrong concept by misunderstanding this line. I will edit this line on the blog so that atleast no misconception is spread.

Collapse
 
suchintan profile image
SUCHINTAN DAS

Thanks peerreynders, for writing this much. It's really a huge chunk of information that you shared and I really appreciate your hard work and efforts.

Collapse
 
brense profile image
Rense Bakker

In your first example, the const card is not HTML, it's a React component, nested inside your Parent. It's not recommended to have nested component definitions and if you absolutely feel that you must do this, you should atleast wrap it inside a useCallback hook to prevent excessive rerenders.

// Very bad for performance:
function Parent(){
  const child = () => <span>this is bad</span>
  return <div>{child()}</div>
}
Enter fullscreen mode Exit fullscreen mode
// useCallback to solve excessive rerenders:
function Parent(){
  const child = useCallback(() => <span>slightly better</span>, [])
  return <div>{child()}</div>
}
Enter fullscreen mode Exit fullscreen mode
// Just define as its own component:
function Child(){
  return <span>I'm a child!</span>
}

function Parent(){
  return <div><Child /></div>
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
suchintan profile image
SUCHINTAN DAS

Thanks Rense , for the sharing the amazing tip. While I was writing that pro tip my idea was to illustrate that we can send a HTML code also as props to our child component to render.

Yes, while taking the example I tried to keep it short , resulting in a bit unclear manner about why to use it.

Collapse
 
brense profile image
Rense Bakker

Oh and your darkMode / lightMode definitions seem like a lot of duplication of code... Why not just do something like this?:

function ToggleButton(props){
  return <i
    className={`fa-solid ${props.icon} ${props.isActive ? 'toogle-active' : 'toogle-inactive'}`}
    onClick={tooglemode}
  />
}

function Toggle(){
  return <div className="toogle">
    <ToggleButton isActive={!dark} icon="fa-moon">
    <ToggleButton isActive={dark} icon="fa-sun">
  </div>
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
suchintan profile image
SUCHINTAN DAS

Right Rense, this would be a better approach to implement that feature. I haven't really thought about implementing it in that manner.

Really appreciate you efforts for sharing this amazing approach with the community 🙂.

Collapse
 
suchintan profile image
SUCHINTAN DAS

Guys if you want me to cover any topic 💭 , you can comment here . I assure you that I maintain a good list of such topics and will surely cover them soon.

I always believe in sharing valuable knowledge with my connections. And if I can share knowledge about a needy topic , it's a pleasure for me .

Do comment below 👇!

Collapse
 
ivadyhabimana profile image
Ivad Yves HABIMANA

React hooks

Collapse
 
suchintan profile image
SUCHINTAN DAS

Sure Ivad, I will cover all the hooks in React over one blog in a broad way. Stay tuned !