I am trying to understand 'render props' in the official React tutorial. There I came across this:
<Mouse>
{mouse => (
<p>The mouse position is {mouse.x}, {mouse.y}</p>
)}
</Mouse>
Could someone elaborate on how this works? I tried substituting it into the preceding example but it raised an error:
class Cat extends React.Component {
render() {
const mouse = this.props.mouse;
return (
<img src="/cat.jpg" style={{ position: 'absolute', left: mouse.x, top: mouse.y }} />
);
}
}
class Mouse extends React.Component {
constructor(props) {
super(props);
this.handleMouseMove = this.handleMouseMove.bind(this);
this.state = { x: 0, y: 0 };
}
handleMouseMove(event) {
this.setState({
x: event.clientX,
y: event.clientY
});
}
render() {
return (
<div style={{ height: '100vh' }} onMouseMove={this.handleMouseMove}>
{/*
Instead of providing a static representation of what <Mouse> renders,
use the `render` prop to dynamically determine what to render.
*/}
{this.props.mouse(this.state)}
</div>
);
}
}
class MouseTracker extends React.Component {
render() {
return (
<div>
<h1>Move the mouse around!</h1>
<Mouse>
{mouse => (
<p>The mouse position is {mouse.x}, {mouse.y}</p>
)}
</Mouse>
</div>
);
}
}
ReactDOM.render(<MouseTracker />, document.querySelector('div'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>
The error received:
this.props.mouse is not a function
You must first understand why people came up with render props. Sometimes you want to create some reusable functionality, without any UI. There is no direct way to do this in react, because normally the components render something. So how do we create a component which renders nothing but still gives you some functionality? Here is an example of very simple render props:
let Increment = props => {
let [counter, setCounter] = React.useState(0);
let increment = () => {
setCounter(ps => ps + 1);
};
return <div>{props.children(counter, increment)}</div>;
};
I just created a counter functionality.
I don't care how users draw this, but I will give them the functionality to read a counter value, and increase it. That's why I use children property to delegate the drawing to the users.
Here is usage:
export default function App() {
return (
<Increment>
{(counter, increment) => {
return (
<div onClick={increment}>
{counter}
</div>
);
}}
</Increment>
);
}
It is up to user to decide how they will draw a counter, but the Increment gives them functionality.