Friday, January 10, 2025
Google search engine
HomeLanguagesHow to access props.children in a stateless functional component in ReactJS ?

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

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.

Let’s understand with the help of a code example. 

Approach: Let’s design a simple Card component. We will pass the data down via [props. children] and see how our cards appear.

  • Create react app named “cards”
  • Create a Button component
  • Create a Card component
  • Create multiple cards in the App component.

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

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

cd cards

Step 2: Modify Your project structure. The Directory structure currently looks like this:

Default Project Structure

We will modify the folder and keep the files we need for this example. Now, make sure your file structure looks like this:

Directory Structure 

This is how the final project structure would look: 

Final Project Structure 

Step 3: Write the following code in index.html. Include the following code in your index.html file, located in the public folder of your project directory.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="utf-8" />
    <meta name="viewport"
          content="width=device-width, initial-scale=1" />
    <meta name="theme-color"
          content="#000000" />
    <meta name="description"
          content="Web site created using create-react-app" />
 
    <title>React App</title>
</head>
 
<body>
     
    <div id="root"></div>
 
</body>
 
</html>


Step 4:  Create the Button Component. Create a new file called Button.js in your src folder. This component will have three buttons. We will use props in the first two buttons using the standard method, passing data from the parent component down to the button component, while in the third button we will use {props. children}. The button component will display anything included within its opening and closing tags.

Add the following code to the Button.js file. 

Javascript




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 5: Create the Card Component. Create a new file Card.js in the src folder. Here we will create a Card component. We will pass data of the card using {props. children}.

Javascript




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;


Step 6: Remove the existing code from your App.js file and replace it with the following code to render the components. We will use the Card component to create four cards. The first card contains text in a <p> tag. The second card has a heading, a horizontal rule, and a subheading. The third card has text in the <h4> tag. The fourth card embeds a button component. In the first two-button components, the standard props are passed, followed by a heading, a horizontal rule, and text in the last button. All elements included within the opening and closing tags will be rendered using {props. children}.

Javascript




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 neveropen</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;


Step 7: Write the following code in index.js file. The index.js file serves as the main entry point, and inside it, the App.js file is rendered at the root ID of the DOM.

Javascript




import React from 'react';
import ReactDOM from 'react-dom';
 
import App from './App';
 
ReactDOM.render(<App />, document.getElementById('root'));


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. 

Implementation of props.children – Working Output

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments