Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How To Pass Props From Parent to Child Component in ReactJS?
Next article icon

How to access props.children in a stateless functional component in ReactJS ?

Last Updated : 31 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The {props. children} allows you to create a generic template, which can be modified by a parent when invoked. In this way, a parent component can easily pass whatever is necessary to its child, even generated layout features. Anytime you call a component, it automatically displays whatever it has between its opening and closing tags. A component with children is always identified with an opening and a closing tag. Each child must go between these two tags.

Props are implemented by defining props in the parent component and passing them down to the next child component and then passing the value again through props in the child component, and then again through the grandchild - which is repeated until the value of the passed value has arrived in the target component. It is a tedious, error-prone process that decreases code flexibility.

Implementation of {props. children}: Implementation is pretty straightforward. Import the child component into the parent component, but instead of invoking it with a self-closing tag, use a standard open/close tag. Information is passed between the opening and closing tags of a child component - in addition to the standard implementation for passing props.

Why do need {props. children} ? 

If we want a flexible component that can store anything between the opening and closing tags of a parent component, that preserves the formatting styles of all its children, then {props. Children} is what we need. There can be instances where you don't know its children in advance so you just pass {props. children} which specifies anything that will be included in between the opening and closing tags. This is used in creating layouts. Standard props cannot specify the styles of other components. It may be necessary to create layouts where certain components remain the same, but the content inside them differs slightly, so creating different components to render data with different styles might not be a good practice. When a component wanted to pass information down to its grandchildren and subsequent children it worked fine until a large number of children grew to the point where many of the props were identical and needed to be modified slightly. It is difficult to comprehend each prop's features when working with hundreds of them. Build layouts with {props. children} and avoid prop drilling. 

Advantages

  • Avoids prop drilling
  • Helps to create compose components
  • Helps in building layouts
  • In order to group unknown similar elements into a parent element.
  • We can use them when the elements are not known in advance.

Prerequisites

  • React JS
  • React JS Functional components

Approach

To access props.children in a stateless functional component in React JS we passs the component as the children to that component and use it from arguments as props.Hence to display that data create a simple Card component. We will pass the data down via [props. children] and see how our cards appear.

Steps to create React Application

Step 1: Create react app "cards". Make a project directory, head over to the terminal, and create a react app named "cards " using the following command:

npx create-react-app cards

Step 2: After the cards app is created, switch to the new folder cards by typing the command below:

cd cards

Project Structure:

Final Project Structure 

Example: This example display some cards to access prop.child in stateless component to display the data on the page.

JavaScript
// Filename - App.js  import Card from "./Card"; import Button from "./Button"; function App() {     return (         <>             {/* card 1 */}             <Card>                 <p                     style={{                         color: "green",                         fontWeight: "bold",                     }}                 >                     Hello,GEEKS!                 </p>             </Card>              {/* card 2  */}             <Card>                 <h1 style={{ color: "green" }}>                     Welcome to GeeksforGeeks                 </h1>                 <hr                     style={{                         borderTop: "dotted 2px green",                     }}                 />                 <h3>                     A computer Science portal for Geeks.{" "}                 </h3>             </Card>              {/* card 3  */}             <Card>                 <h4>                     It contains well written , well thought                     and well explained computer science                     articles.                 </h4>             </Card>              {/* card 4 */}             <Card>                 <Button                     button1="Explore Courses"                     button2="Read Articles"                 >                     <h3 style={{ color: "Blue" }}>                         CONTRIBUTE                     </h3>                     <hr                         style={{                             borderTop: "dotted 2px green",                         }}                     />                     Pick suggested articles and get started                     .                 </Button>             </Card>         </>     ); } export default App; 
JavaScript
// Filename - Card.js  import React from "react";  const Card = (props) => {     return (         <div             style={{                 width: "30%",                 margin: " 30px auto 20px auto",                 boxShadow:                     "0 5px 10px 2px rgba(0,0,0,0.25) ",                 padding: "20px",                 textAlign: "center",             }}         >             {props.children}         </div>     ); }; export default Card; 
JavaScript
// Filename - Button.js  import React from "react";  const buttonstyle = {     backgroundColor: "white",     border: "2px solid #4CAF50",     color: "black",     padding: "4px",     textAlign: "center",     fontSize: "16px",     margin: "4px 2px",     cursor: "pointer", };  const Button = (props) => {     return (         <div>             <button style={buttonstyle}>                 {props.button1}             </button>             <button style={buttonstyle}>                 {props.button2}             </button>             <button style={buttonstyle}>                 {props.children}             </button>         </div>     ); };  export default Button; 

Step to run the application: Now let us run our application by using the following command.

npm start

Output: By default, the React project will run on port 3000. You can access it at localhost:3000 on your browser. You will see, the data on each card differs, but the layout remains the same. The content of the cards is formatted differently. 


Next Article
How To Pass Props From Parent to Child Component in ReactJS?
author
codesaurav
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • Geeks Premier League
  • Geeks-Premier-League-2022
  • React-Questions

Similar Reads

  • How to access props inside a functional component?
    React is an open-source JavaScript library that is mainly used for developing User Interface or UI components. It is a single-page application that is popularly used for developing dynamic web interfaces. While building a React application, the React components serve as basic building blocks. In Rea
    3 min read
  • How To Get Previous State In ReactJS Functional Component?
    To get the previous state in ReactJS Functional Component we can use the previous value of the state while using the set state method. State can only be directly accessed in the class component so we will be using the react useState hook to accomplish the task. PrerequisitesReact JSReact JS function
    2 min read
  • How to set Parent State from Children Component in ReactJS?
    To set the parent state from a child component, we use React’s unidirectional data flow. Instead of directly passing data, we pass a function that enables the child to send data back to set the parent state. Prerequisites:React JSuseState HookApproachTo set parent state from child component in React
    2 min read
  • How to use PropTypes in a Functional Component in React?
    PropTypes is a mechanism provided by React for type-checking props passed to components. It allows developers to specify the expected types of props (such as strings, numbers, arrays, objects, etc.) and whether they are required or optional. PropTypes helps catch bugs early by providing warnings in
    2 min read
  • How To Pass Props From Parent to Child Component in ReactJS?
    ReactJS is a powerful library that helps developers build interactive user interfaces by breaking them into reusable components. One of the essential features of React is the ability to pass data between components using props. In React, props allow parent components to send data or functions to chi
    4 min read
  • How to convert functional component to class component in ReactJS ?
    ReactJS offers two primary ways of creating components: functional components and class components. While functional components are more concise and easier to reason about, there are situations where class components may be necessary with the flexibility to use lifecycle methods and manage the state
    2 min read
  • How to Call Parent Components's Function from Child Component in React ?
    In React, it is very important to manage communication between components for building flexible and maintainable applications. Sometime, you need to trigger a function defined in a parent component from a child component. In this article, we'll see how to achieve this in React by passing down functi
    3 min read
  • What is a pure functional component in ReactJS ?
    What is a JavaScript function? A JavaScript function is a block of code designed to perform a particular task which is executed when it is called. How React functional components are similar to JavaScript functions? Conceptually, components are like JavaScript functions.  A functional component is a
    3 min read
  • How to change states with onClick event in ReactJS using functional components ?
    In modern web applications, to change states with onClick event in React JS using functional components is done by Hooks in React as the functional components don't have inbuilt states like class components. With Hooks, state objects are completely independent of each other, so you can have as many
    2 min read
  • Different ways to access props inside a Component in React
    The props keyword is the shorthand for properties. It is one of the most important features of React which helps in effective communication between various React components. It is a read-only attribute for passing data from the parent component to the child component. There are various ways to acces
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences