Currently working on a CV Creator as a mini React project, these are my current Components:
Creator
Form
Input
CvDisplay
(DisplayComponents)
I have a state in my Input component that updates upon every change in the input box, this is a simplified example of the component:
export default function Input() {
const [inputValue, setInputValue] = useState("");
const handleInputChange(e) => {
setInputValue(e.target.value);
}
return (
<div>
<input type="text" onChange={handleInputChange} />
</div>
)
}
I am trying to get the inputValue state to the Creator component, and then into the CvDisplay component, so when the inputValue changes from the Input component, the changes will display in real time in the CvDisplay component. An example of it being done would be here: https://cv-app-eta.vercel.app/
Beginner here so I would appreciate any advice, thank you!
I tried using a callback function, but it did not work as expected as there are multiple Input Components in the Form component.
Also tried lifting up the state, but could not manage to make it work as it’s technically a "grandparent to child" component instead of a parent to child component.
2
Answers
You can make use of the context api or redux toolkit to do this in easy way but as you say that you are a beginner you can make the inputValue state in the parent component and then pass it as a prop to the child component.
In this state you can do in couple of ways like using some state management like the biuld-in
Context
api of the React, or a pacakeges likeRedux
orZustand
. but those pacakeges are somewhat complex and as you are beginner you can make it simple, if your parent components can be putted in another parent component and you can create the state in there and pass the state to the both the parents and those parents they will pass to their childs.Here’s an example of how you might structure your components:
Creator Component:
This is where you’ll manage the state and handle the changes. It will pass down the state and a function to update the state to the
Form
component.Form Component:
This component will receive the
inputValue
andonInputChange
function as props. It can then pass them down to theInput
component.Input Component:
This component receives
inputValue
andonInputChange
as props. When the input changes, it callsonInputChange
to update the state in theCreator
component.CvDisplay Component:
This component receives
inputValue
as a prop and displays it.Now, whenever the input value changes, it will update the state in the
Creator
component, and the updated value will be passed down to theCvDisplay
component, allowing you to see the changes in real-time.