SlideShare a Scribd company logo
REACT RENDER PROP
By Saikat Samanta
Knowledge required:
1. Basic of React Js.
2. Typescript
Point to note:
1. In this presentation we are going to use typescript to create the examples.
2
What is render prop?
The term “render prop” refers to a technique for sharing code between React
components using a prop whose value is a function.
So, we have two things here:
1. Sharing code by using prop.
2. Prop value will be a function.
Let’s simplify it...
3
Sharing code by using Prop
// Child component
export function Component(props: { name: JSX.Element})
{
return <div>{props.name}</div>;
}
// Parent component
export default function App() {
return (
<div className="App">
<Component name={<p>John</p>} />
</div>
);
}
4
Prop value will be a function
// Child component
export function Component(props: { name: () => JSX.Element }) {
return <div>{props.name()}</div>;
}
// Parent component
export default function App() {
return (
<div className="App">
<Component name={() => <p>John</p>} />
</div>
);
}
5
Prop value will send from child component
// Child component
export function Component(props: { name: (name: string ) => JSX.Element }) {
return <div>{props.name("John")}</div>;
}
// Parent component
export default function App() {
return (
<div className="App">
<Component name={(name) => <p>{name}</p>} />
</div>
);
}
6
Now, we have the some idea about, what render prop definition mean.
So, it’s saying, we can share code between react components with the help of prop and
prop value will be a function.
Let’s see how render prop help to share
code between components. 🤔
7
Let’s take an example:
We have two tasks:
1. We need to implement a component which will count how many times a button
clicked.
2. We have a header and it will count how many times we hover on it.
8
1. Button click counter:
// Child component
export function ClickCounter() {
const [count, setCount] = useState(0);
const addCount = () => {
setCount(prevCount => prevCount + 1);
}
return (
<div>
<button onClick={addCount}>
You click {count} time
</button>
</div>
);
}
// Parent component
export default function App() {
return (
<div className="App">
<ClickCounter/>
</div>
);
}
repeated code
9
2. Hover counter
// Child component
export function HoverCounter() {
const [count, setCount] = useState(0);
const addCount = () => {
setCount(prevCount => prevCount + 1);
}
return (
<div onMouseEnter={addCount}>
<p>Hover {count} times</p>
</div>
);
}
// Parent component
export default function App() {
return (
<div className="App">
<HoverCounter/>
</div>
);
}
repeated code
10
Here, we are repeating a code block in both component. To avoid this situation `render
prop`comes into picture.
By using `render prop` we will share the same piece of code with both components.
Let’s see … 🤔
11
Remove the repeated part:
Removed the repeated part and replace with props in ClickCounter.
export function ClickCounter({
count,
onClick,
}: {
count: number;
onClick: React.MouseEventHandler<HTMLButtonElement>;
}) {
return (
<div>
<button onClick={onClick}>You click {count} time</button>
</div>
);
}
12
Remove the repeated part:
Removed the repeated part and replace with props in HoverCounter.
export function HoverCounter({
count,
onMouseHover,
}: {
count: number;
onMouseHover: React.MouseEventHandler<HTMLDivElement>;
}) {
return (
<div onMouseEnter={onMouseHover}>
<p>Hover {count} times</p>
</div>
);
}
13
Create a common counter component:
export function Counter(props: {
render: (count: number, addCount: () => void) => JSX.Element;
}) {
// Count logic
const [count, setcount] = useState(0);
const addCount = () => {
setcount((prevState) => prevState + 1);
};
// End logic
return <div>{props.render(count, addCount)}</div>;
}
14
Let’s use the common counter:
Let’s use the common counter component in parent component.
export default function App() {
return (
<div className="App">
<Counter
render={(count, setCount) => (
<ClickCounter count={count} onClick={setCount} />
)}
/>
<Counter
render={(count, setCount) => (
<HoverCounter count={count} onMouseHover={setCount} />
)}
/>
</div>
);
}
15
Result:
Here, we don’t repeat the same code but both components are working as expected.
16
Conclusion:
1. `Render props` will be very helpful to avoid code repetition.
2. We can share code in any level of component tree no need to be a direct child.
3. This will help to write code in more organized way without code repetition.
17
Reference:
1. https://reactjs.org/docs/render-props.html
2. https://blog.logrocket.com/react-reference-guide-render-props/
3. https://flexiple.com/react/render-props-an-advanced-react-pattern/
18
Question? ♂️
19
Thank you...
20
Ad

More Related Content

What's hot (20)

Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
NexThoughts Technologies
 
Intro to React
Intro to ReactIntro to React
Intro to React
Eric Westfall
 
Let's Redux!
Let's Redux!Let's Redux!
Let's Redux!
Joseph Chiang
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
DivyanshGupta922023
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hook
Piyush Jamwal
 
React js t2 - jsx
React js   t2 - jsxReact js   t2 - jsx
React js t2 - jsx
Jainul Musani
 
React & Redux JS
React & Redux JS React & Redux JS
React & Redux JS
Hamed Farag
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
Walking Tree Technologies
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
Knoldus Inc.
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
Soluto
 
React and redux
React and reduxReact and redux
React and redux
Mystic Coders, LLC
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
Ignacio Martín
 
React workshop
React workshopReact workshop
React workshop
Imran Sayed
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
Sergey Romaneko
 
Intro to React
Intro to ReactIntro to React
Intro to React
Justin Reock
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
洪 鹏发
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
MicroPyramid .
 
react redux.pdf
react redux.pdfreact redux.pdf
react redux.pdf
Knoldus Inc.
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular Components
Squash Apps Pvt Ltd
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesome
Andrew Hull
 
React js use contexts and useContext hook
React js use contexts and useContext hookReact js use contexts and useContext hook
React js use contexts and useContext hook
Piyush Jamwal
 
React & Redux JS
React & Redux JS React & Redux JS
React & Redux JS
Hamed Farag
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
Walking Tree Technologies
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
Knoldus Inc.
 
React new features and intro to Hooks
React new features and intro to HooksReact new features and intro to Hooks
React new features and intro to Hooks
Soluto
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
洪 鹏发
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
MicroPyramid .
 
Sharing Data Between Angular Components
Sharing Data Between Angular ComponentsSharing Data Between Angular Components
Sharing Data Between Angular Components
Squash Apps Pvt Ltd
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesome
Andrew Hull
 

Similar to React render props (20)

Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Ontico
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
Christoffer Noring
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
Jeado Ko
 
React: JSX and Top Level API
React: JSX and Top Level APIReact: JSX and Top Level API
React: JSX and Top Level API
Fabio Biondi
 
2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack
Codifly
 
Ways to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptxWays to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptx
BOSC Tech Labs
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2
Paras Mendiratta
 
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
Edureka!
 
Advanced React Component Patterns - ReactNext 2018
Advanced React Component Patterns - ReactNext 2018Advanced React Component Patterns - ReactNext 2018
Advanced React Component Patterns - ReactNext 2018
Robert Herbst
 
Introduction to React for Frontend Developers
Introduction to React for Frontend DevelopersIntroduction to React for Frontend Developers
Introduction to React for Frontend Developers
Sergio Nakamura
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
[T]echdencias
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
Ignacio Martín
 
3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components
Surendra kumar
 
Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and Symfony
Ignacio Martín
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
TO THE NEW Pvt. Ltd.
 
React native app with type script tutorial
React native app with type script tutorialReact native app with type script tutorial
React native app with type script tutorial
Katy Slemon
 
React native introduction
React native introductionReact native introduction
React native introduction
InnerFood
 
React redux
React reduxReact redux
React redux
Michel Perez
 
React outbox
React outboxReact outbox
React outbox
Angela Lehru
 
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)
Ontico
 
[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법[FEConf Korea 2017]Angular 컴포넌트 대화법
[FEConf Korea 2017]Angular 컴포넌트 대화법
Jeado Ko
 
React: JSX and Top Level API
React: JSX and Top Level APIReact: JSX and Top Level API
React: JSX and Top Level API
Fabio Biondi
 
2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack2018 05-16 Evolving Technologies: React, Babel & Webpack
2018 05-16 Evolving Technologies: React, Babel & Webpack
Codifly
 
Ways to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptxWays to Set Focus on an Input Field After Rendering in React.pptx
Ways to Set Focus on an Input Field After Rendering in React.pptx
BOSC Tech Labs
 
Angular JS2 Training Session #2
Angular JS2 Training Session #2Angular JS2 Training Session #2
Angular JS2 Training Session #2
Paras Mendiratta
 
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React on...
Edureka!
 
Advanced React Component Patterns - ReactNext 2018
Advanced React Component Patterns - ReactNext 2018Advanced React Component Patterns - ReactNext 2018
Advanced React Component Patterns - ReactNext 2018
Robert Herbst
 
Introduction to React for Frontend Developers
Introduction to React for Frontend DevelopersIntroduction to React for Frontend Developers
Introduction to React for Frontend Developers
Sergio Nakamura
 
React & Redux for noobs
React & Redux for noobsReact & Redux for noobs
React & Redux for noobs
[T]echdencias
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
Visual Engineering
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
Ignacio Martín
 
3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components3 Simple Steps to follow to Create React JS Components
3 Simple Steps to follow to Create React JS Components
Surendra kumar
 
Server side rendering with React and Symfony
Server side rendering with React and SymfonyServer side rendering with React and Symfony
Server side rendering with React and Symfony
Ignacio Martín
 
React native app with type script tutorial
React native app with type script tutorialReact native app with type script tutorial
React native app with type script tutorial
Katy Slemon
 
React native introduction
React native introductionReact native introduction
React native introduction
InnerFood
 
Ad

Recently uploaded (20)

Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Build Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For DevsBuild Your Own Copilot & Agents For Devs
Build Your Own Copilot & Agents For Devs
Brian McKeiver
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Ad

React render props

  • 1. REACT RENDER PROP By Saikat Samanta
  • 2. Knowledge required: 1. Basic of React Js. 2. Typescript Point to note: 1. In this presentation we are going to use typescript to create the examples. 2
  • 3. What is render prop? The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function. So, we have two things here: 1. Sharing code by using prop. 2. Prop value will be a function. Let’s simplify it... 3
  • 4. Sharing code by using Prop // Child component export function Component(props: { name: JSX.Element}) { return <div>{props.name}</div>; } // Parent component export default function App() { return ( <div className="App"> <Component name={<p>John</p>} /> </div> ); } 4
  • 5. Prop value will be a function // Child component export function Component(props: { name: () => JSX.Element }) { return <div>{props.name()}</div>; } // Parent component export default function App() { return ( <div className="App"> <Component name={() => <p>John</p>} /> </div> ); } 5
  • 6. Prop value will send from child component // Child component export function Component(props: { name: (name: string ) => JSX.Element }) { return <div>{props.name("John")}</div>; } // Parent component export default function App() { return ( <div className="App"> <Component name={(name) => <p>{name}</p>} /> </div> ); } 6
  • 7. Now, we have the some idea about, what render prop definition mean. So, it’s saying, we can share code between react components with the help of prop and prop value will be a function. Let’s see how render prop help to share code between components. 🤔 7
  • 8. Let’s take an example: We have two tasks: 1. We need to implement a component which will count how many times a button clicked. 2. We have a header and it will count how many times we hover on it. 8
  • 9. 1. Button click counter: // Child component export function ClickCounter() { const [count, setCount] = useState(0); const addCount = () => { setCount(prevCount => prevCount + 1); } return ( <div> <button onClick={addCount}> You click {count} time </button> </div> ); } // Parent component export default function App() { return ( <div className="App"> <ClickCounter/> </div> ); } repeated code 9
  • 10. 2. Hover counter // Child component export function HoverCounter() { const [count, setCount] = useState(0); const addCount = () => { setCount(prevCount => prevCount + 1); } return ( <div onMouseEnter={addCount}> <p>Hover {count} times</p> </div> ); } // Parent component export default function App() { return ( <div className="App"> <HoverCounter/> </div> ); } repeated code 10
  • 11. Here, we are repeating a code block in both component. To avoid this situation `render prop`comes into picture. By using `render prop` we will share the same piece of code with both components. Let’s see … 🤔 11
  • 12. Remove the repeated part: Removed the repeated part and replace with props in ClickCounter. export function ClickCounter({ count, onClick, }: { count: number; onClick: React.MouseEventHandler<HTMLButtonElement>; }) { return ( <div> <button onClick={onClick}>You click {count} time</button> </div> ); } 12
  • 13. Remove the repeated part: Removed the repeated part and replace with props in HoverCounter. export function HoverCounter({ count, onMouseHover, }: { count: number; onMouseHover: React.MouseEventHandler<HTMLDivElement>; }) { return ( <div onMouseEnter={onMouseHover}> <p>Hover {count} times</p> </div> ); } 13
  • 14. Create a common counter component: export function Counter(props: { render: (count: number, addCount: () => void) => JSX.Element; }) { // Count logic const [count, setcount] = useState(0); const addCount = () => { setcount((prevState) => prevState + 1); }; // End logic return <div>{props.render(count, addCount)}</div>; } 14
  • 15. Let’s use the common counter: Let’s use the common counter component in parent component. export default function App() { return ( <div className="App"> <Counter render={(count, setCount) => ( <ClickCounter count={count} onClick={setCount} /> )} /> <Counter render={(count, setCount) => ( <HoverCounter count={count} onMouseHover={setCount} /> )} /> </div> ); } 15
  • 16. Result: Here, we don’t repeat the same code but both components are working as expected. 16
  • 17. Conclusion: 1. `Render props` will be very helpful to avoid code repetition. 2. We can share code in any level of component tree no need to be a direct child. 3. This will help to write code in more organized way without code repetition. 17