Skip to content

Instantly share code, notes, and snippets.

@react-ram
Created July 22, 2019 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save react-ram/aa318282d22981dfaee48bdb151abafb to your computer and use it in GitHub Desktop.
Save react-ram/aa318282d22981dfaee48bdb151abafb to your computer and use it in GitHub Desktop.
render props example
import React, { Component } from "react";
import Counter from "./Counter";
import ClickCounter from "./ClickCounter";
import HoverCounter from "./HoverCounter";
class App extends Component {
render() {
return (
<div>
<Counter
render={(count, incrementCount) => (
<ClickCounter count={count} incrementCount={incrementCount} />
)}
/>
<Counter
render={(count, incrementCount) => (
<HoverCounter count={count} incrementCount={incrementCount} />
)}
/>
</div>
);
}
}
export default App;
import React, { Component } from "react";
class ClickCounter extends Component {
render() {
const { count, incrementCount } = this.props;
return (
<div>
<button onClick={incrementCount}>clicked {count} times</button>
</div>
);
}
}
export default ClickCounter;
import React, { Component } from "react";
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
incrementCount = () => {
this.setState(prevState => ({ count: prevState.count + 1 }));
};
render() {
return (
<div>{this.props.render(this.state.count, this.incrementCount)}</div>
);
}
}
export default Counter;
import React, { Component } from "react";
class HoverCounter extends Component {
render() {
const { count, incrementCount } = this.props;
return (
<div>
<h2 onMouseOver={incrementCount}>hovered {count} times</h2>
</div>
);
}
}
export default HoverCounter;
@react-ram
Copy link
Author

The term “render prop” refers to a technique for sharing code between React components using a prop whose value is a function.A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment