23
loading...
This website collects cookies to deliver better user experience
function App() {
return (
<div>
<RandomNumber render={
function(number) {
return (
<h1>{number > 0 ? "Whoa, Big Guy!" : "Nah, less than one, Nice Try!"}</h1>
)
}
}/>
</div>
)
}
function RandomNumber(props) {
const max = Math.random()
const min = Math.random()
const number = max - min
return (
<div>
{props.render(number)}
</div>
)
}
ReactDOM.render(<App />,document.getElementById('root'))
<App />
that contains a child component <RandomNumber />
. The child component <RandomNumber />
will manage the state of the random number, but it will not care whether <App />
is rendering the display of it or another parent component.
The parent component <App />
will manage the display of the random number and the corresponding message. It will however not maintain the state of the random number.
<RandomNumber />
component across three parent components? Let's see what it looks like below.function App() {
return (
<>
<ParentOne />
<ParentTwo />
<ParentThree />
</>
)
}
function ParentOne() {
return (
<div>
<RandomNumber render={
function(number) {
return (
<h1>{number > 0 ? "Whoa, Big Guy!" : "Nah, less than one, Nice Try!"}</h1>
)
}
}/>
</div>
)
}
function ParentTwo() {
return (
<div>
<RandomNumber render={
function(number) {
return (
<h1>{number > 0 ? "Whoa, Big Guy!" : "Nah, less than one, Nice Try!"}</h1>
)
}
}/>
</div>
)
}
function ParentThree() {
return (
<div>
<RandomNumber render={
function(number) {
return (
<h1>{number > 0 ? "Whoa, Big Guy!" : "Nah, less than one, Nice Try!"}</h1>
)
}
}/>
</div>
)
}
function RandomNumber(props) {
const max = Math.random()
const min = Math.random()
const number = max - min
return (
<div>
{props.render(number)}
</div>
)
}
ReactDOM.render(<App />,document.getElementById('root'))
<RandomNumber />
child component did not have to change to accommodate each parent. It simply maintains a random number for each parent component. Each parent component, in turn, manages the rendering of the JSX separately and independent of each other.