-
Notifications
You must be signed in to change notification settings - Fork 32
/
react_lifting_state_children_function.html
75 lines (66 loc) · 2.17 KB
/
react_lifting_state_children_function.html
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
<!DOCTYPE html>
<html>
<head>
<title>Lifting State Example</title>
<style>
.temp {
margin-top: 10px;
font-weight: bold;
}
</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/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
// Input component using children as a function
function Input(props) {
const [value, setValue] = React.useState("");
return (
<div>
<input
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="Temp in °C"
/>
{props.children(value)}
</div>
);
}
// Kelvin component
function Kelvin({ value = 0 }) {
return <div className="temp">{Number(value) + 273.15}K</div>;
}
// Fahrenheit component
function Fahrenheit({ value = 0 }) {
return <div className="temp">{(Number(value) * 9) / 5 + 32}°F</div>;
}
// App component
function App() {
return (
<div className="App">
<h1>Temperature Converter</h1>
<Input>
{(value) => (
<>
<Kelvin value={value} />
<Fahrenheit value={value} />
</>
)}
</Input>
</div>
);
}
// Render the App component
ReactDOM.render(<App />, document.getElementById("root"));
</script>
</body>
</html>
<!--
In this updated example, instead of using a separate render prop, we utilize the children prop of the Input component. We pass a function as a child to the Input component, and this function receives the input value as an argument.
The Input component renders an input field and calls the props.children function, passing the input value as an argument. The child function can then handle the value and render the Kelvin and Fahrenheit components accordingly.
The App component remains the same, rendering the Input component and providing the child function through the children prop.
-->