Next.js Discord

Discord Forum

How can i pass a value to a parent component

Answered
Arboreal ant posted this in #help-forum
Open in Discord
Arboreal antOP
I want to make a settings page. I have a page.js file, and from there I render a component called "settings" . In that component, I have all of the field components. Now, I could just directly put them in the form component, but then they wouldn't be reusable. The 'Save Changes' button is also in the settings component, on click I want to send an API request to my endpoint that contains all of the values from the field components.
Answered by B33fb0n3
you can have a parent components, that holds all the current settings and the single setting components handles the functionality of the specific settings. The value comes from top and also the change function that will be executed on change comes from top. If you now change the value, the specific setting will be changed
View full answer

13 Replies

@Arboreal ant I want to make a settings page. I have a page.js file, and from there I render a component called "settings" . In that component, I have all of the field components. Now, I could just directly put them in the form component, but then they wouldn't be reusable. The 'Save Changes' button is also in the settings component, on click I want to send an API request to my endpoint that contains all of the values from the field components.
you can have a parent components, that holds all the current settings and the single setting components handles the functionality of the specific settings. The value comes from top and also the change function that will be executed on change comes from top. If you now change the value, the specific setting will be changed
Answer
@Arboreal ant wdym by "single setting components handles the functionality of the specific settings" so what component makes the api request?
I thought that you parent component will make the api call?

My „settings component“ is your „field component“. So the component that renders the setting/field and adds functionality
@Arboreal ant yes but how will that top component know the values of the fields?
Because the top component passes the value and the value change function down
@B33fb0n3 Because the top component passes the value and the value change function down
Arboreal antOP
ah okay, could you just give me an example of how the field compoent would look?
@Arboreal ant ah okay, could you just give me an example of how the field compoent would look?
Yea, in pseudocode it’s:

parent:
useState with all settings as object

onChange function, that updates the key inside the object of the useState

return: a map of RenderSetting-Component with props of value and onChange

RenderSetting-Component (for example for text):

return: Input Element with value from props. OnChange calls the onChange function from props.
Yes
Arboreal antOP
okay i understand now, thank you
Does that solves your problem?
happy to help