DEV Community

Cover image for render prop and children in react
aravind_akay
aravind_akay

Posted on

2 1

render prop and children in react

render prop

Hello guys I want to give an introduction about what render prop is.

According to the official documentation

The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function.

From my point of view its just an another prop but it will share some of the code but you can name it whatever you want as prop.

Foe an example,

import "./styles.css";
import ListItem from "./ListItem";

export default function App() {
  return (
    <div className="App">
      <ListItem render={"Simply a prop"} />

    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

The output is

Image description

Traditionally it has been used as this following way,

In App.js
<ListItem render={(data) => <li>{data}</li>}  data="Simply a prop"/>

In ListItem.js
const ListItem = (props) => {
  return <div> {props.render(props.data)}</div>;
};
Enter fullscreen mode Exit fullscreen mode

The output is

Image description

I think that solves your doubts with render prop.

children prop

children prop is nothing but the ui rendered between the elements. what do I mean by that. Lets say you have a div in between you write a lot of code , all the codes you've written between that div is children to that div.

Apply the same logic for components.

For example consider the same ListItem component,

//In App.js

<ListItem> <div>Hello Guys , this is considered as the children </div> </ListItem>

//In ListItem.js

const ListItem = (props) => {
  return <div> {props.children}</div>;
};

Enter fullscreen mode Exit fullscreen mode

The output is

Image description

I think you should try this example and comment if there is any doubt. Happy coding.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay