My intention here is to create a search component page, that has a form and a table, that can vary on fields and result.
Let’s supose a component that receive a couple of children:
const SearchPage = ({title}) => {
function handleSubmit() {...}
return (
<div>
<div className="form">
{chindren[0]}
</div>
<div className="table">
{children[1]}
</div>
</div>
)
}
and now using this component:
const MyPage = () => {
return (
<SearchPage title="Search for fruits">
<form onSubmit={handleSubmit}> <!--this is children[0]-->
<input useSomethingFromSearchPageHere></input>
....
</form>
<table> <!--this is children[1]-->
....
</table>
</SearchPage>
)
}
How access SearchPage variables and methods from children fragments?
This is the right way of doing this?
2
Answers
How about using props, i know this goes against question but it is the best way to do this. I also added types for clarity but please omit if not using typescript.
To achieve your goal of accessing SearchPage variables and methods from its children components, you can utilize React’s context system.
First, define a new context that will be used to pass the handleSubmit method and any other necessary data or methods.
Update the SearchPage component to use the SearchPageContext.Provider to pass down the handleSubmit method and any other necessary state or functions.
In your child components (e.g., the form inside MyPage), you can now use the useSearchPage hook to access handleSubmit and any other data or methods you’ve provided.