-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathreact_render_props2.html
More file actions
86 lines (77 loc) · 2.71 KB
/
react_render_props2.html
File metadata and controls
86 lines (77 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<!DOCTYPE html>
<html>
<head>
<title>Render Props Example</title>
<style>
.container {
display: flex;
flex-wrap: wrap;
}
.image {
width: 200px;
margin: 10px;
}
</style>
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
// DogImages component using render prop
class DogImages extends React.Component {
state = {
images: [],
loading: true
};
componentDidMount() {
this.fetchDogImages();
}
fetchDogImages = async () => {
try {
const response = await axios.get("https://dog.ceo/api/breeds/image/random/5");
const images = response.data.message;
this.setState({ images, loading: false });
} catch (error) {
console.log("Error fetching dog images", error);
}
};
render() {
const { images, loading } = this.state;
return this.props.render(images, loading);
}
}
// App component
function App() {
return (
<div className="App">
<h1>Dog Images</h1>
<DogImages
render={(images, loading) => (
<div>
{loading ? (
<div>Loading...</div>
) : (
<div className="container">
{images.map((image, index) => (
<img src={image} alt={`Dog ${index + 1}`} key={index} className="image" />
))}
</div>
)}
</div>
)}
/>
</div>
);
}
// Render the App component
ReactDOM.render(<App />, document.getElementById("root"));
</script>
</body>
</html>
<!--
In this example, we have a DogImages component that uses a render prop. Inside the DogImages component, we fetch multiple pictures of dogs from the Unsplash API using Axios. Once the data is fetched, we update the component's state with the array of images. The component also manages a loading state to show a loading message while the data is being fetched.
The App component is where we use the DogImages component. We pass a render prop to the DogImages component, which receives the images array and loading flag as arguments. Based on the loading flag, we conditionally render either a loading message or a container with the dog images. Each image is rendered as an <img> element with a unique src and alt text.
-->