Skip to content

Instantly share code, notes, and snippets.

@Shalabyelectronics
Created May 2, 2023 23:28
Show Gist options
  • Save Shalabyelectronics/e28dc1e1ed08063ebbc201929535a6dc to your computer and use it in GitHub Desktop.
Save Shalabyelectronics/e28dc1e1ed08063ebbc201929535a6dc to your computer and use it in GitHub Desktop.
Practicing Lifthing State up with React Js
import React, { useState } from "react";
const Child = ({ resize, resizeParenObj }) => {
const { setResizeParent, resizeBox: resizeParent } = resizeParenObj;
return (
<div
style={{
width: `${resize}px`,
height: `${resize}px`,
margin: 10,
backgroundColor: "black",
color: "#fff",
padding: 10,
fontSize: 20,
fontWeight: 600,
textAlign: "center",
}}
>
<h3>Child</h3>
<button
onClick={() => {
resizeParent("increase", setResizeParent);
}}
>
+
</button>
<button
onClick={() => {
resizeParent("decrease", setResizeParent);
}}
>
-
</button>
</div>
);
};
const Parent = () => {
const [resizeChild, setResizeChild] = useState(150);
const [resizeParent, setResizeParent] = useState(150);
const resizeBox = (action, setStateHook) => {
switch (action) {
case "increase":
setStateHook((prevState) => prevState + 20);
break;
case "decrease":
setStateHook((prevState) => prevState - 20);
break;
}
};
return (
<div
style={{ display: "flex", flexDirection: "column", alignItems: "center" }}
>
<h1>Props and Lifting state up</h1>
<div
style={{
width: `${resizeParent}px`,
height: `${resizeParent}px`,
margin: 10,
backgroundColor: "red",
padding: 10,
fontSize: 20,
fontWeight: 600,
textAlign: "center",
}}
>
<h3>Parent</h3>
<button
onClick={() => {
resizeBox("increase", setResizeChild);
}}
>
+
</button>
<button
onClick={() => {
resizeBox("decrease", setResizeChild);
}}
>
-
</button>
</div>
<Child
resize={resizeChild}
resizeParenObj={{ setResizeParent, resizeBox }}
/>
</div>
);
};
export default Parent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment