I would like to send the variable "synonym", which I have collected in this event, to another component. The component is not directly linked to this one, it is in fact a parent of a parent.
Ideally, this word will update the state on the other component so I can run the API again, with this new word.
export default function Synonym(props) {
function searchSynonym(event) {
let synonym = event.target.innerHTML;
}
if (props.synonyms.length > 0) {
return (
<div className="Synonym">
{props.synonyms.map((word, index) => {
if (index < 10) {
return (
<button
key={index}
className="synonym-word"
onClick={searchSynonym}
>
{word}
</button>
);
} else return null;
})}
</div>
);
} else return null;
}
Full code is open-sources on GitHub. The component I am trying to send word to is Search.js
Thank you in advance, I'm very new to React!
CodePudding user response:
The processes for passing data from a child component to a parent component are as follows:
- Create a callback function in the parent component. The data will be retrieved from the child component using this callback function.
- As a prop from the parent component, pass the callback function to the child.
- Using props, the child component calls the parent callback function and return data to the parent component.
In your situation The straightforward and simple solution is to create a callback function in the Search component that you want to use the "Synonym" and then pass the function as a prop to the Definitions component and then pass it to the Synonym component again.
like the following!
In Search Component create a synonym useState and create getSynonym callback function the pass it as prop to the Definitions component.
export default function Search() {
const [keyword, setKeyword] = useState("");
const [result, setResult] = useState(null);
const [photos, setPhotos] = useState(null);
const [synonym, setSynonym] = useState(null);
const getSynonym = (value) =>{
setSynonym(value)
}
{....}
return (
<div className="Search">
<form onSubmit={handleSearch}>
<input className="input" type="search" onChange={updateCity} />
</form>
<Definitions data={result} getSynonym={getSynonym}/>
<Pictures data={photos} />
</div>
);
}
In Definations component pass callback function to the Synonym component again.
export default function Definitions(props) {
{...}
return (
{...}
<Synonym synonyms={meaning.definitions[0].synonyms} getSynonym={props.getSynonym} />
{...}
);
}
In Synonym component calls the callback function.
export default function Synonym(props) {
function searchSynonym(event) {
let synonym = event.target.innerHTML;
props.getSynonym(synonym)
}
{...}
}
