Passing props is a more complicated method for some beginners. Some people easily pass the props from parents to child just like that.
Pass props parents to child
const Child = ({myProps})=>{
return(
<h1>{myProps}</h1>
)
}
export default function App() {
return (
<div className="App">
<h1>Code Components</h1>
<h2>Make eassy your codding life!</h2>
<Child myProps={"codecomponents.in"}/>
</div>
);
}
Another way to pass props parents to child
const Child = (props)=>{
return(
<h1>{props.myProps}</h1>
)
}
export default function App() {
return (
<div className="App">
<h1>Code Components</h1>
<h2>Make eassy your codding life!</h2>
<Child myProps={"codecomponents.in"}/>
</div>
);
}
Pass Props child to parents
But the issue is when people try to pass props from child to parent, they often make a mistake. Here, I solve the issue.
import { useState } from "react";
const Child = ({ onDataFromChild }) => {
const sendDataToParent = () => {
const data = "codecomponents.in";
onDataFromChild(data);
};
return <button onClick={sendDataToParent}>Send Props</button>;
};
export default function App() {
const [dataFromChild, setDataFromChild] = useState();
const handleDataFromChild = (data) => {setDataFromChild(data);};
return (
<div className="App">
<Child onDataFromChild={handleDataFromChild} />
<h2>Child Data is :- {dataFromChild}</h2>
</div>
);
}
That's the best communication between a parent and a child component in React.