Reputation: 528
I have two component in my project. I have below component in my 1st component
import React, { useContext, useState, useEffect, useMemo, useRef } from "react";
function Invoice() {
const accordionRef = useRef(null);
const toggleAccordion = () => {
accordionRef.current.click();
}
}
2nd component
import React, { useContext, useState, useEffect, useMemo, useRef } from "react";
function Modal() {
toggleAccordion ();
}
}
I need to call 'toggleAccordion()' function inside the second component. how i do it
Upvotes: 0
Views: 781
Reputation: 1160
You can manage your components with props which are the part of app state. In case you change something inside you child component depending on events or data in the parent one you should pass the proper props:
const Child = ({color}) => <p style={{"color":color}}>{color}</p>
const Parent = () => {
const [childColor, setChildColor] = useState("#faa")
return <Child color={childColor} />
}
Finally, you may also send you function from the parent component as the prop In the example above you utilize the prop "color" just to show the data. But also you can check the new value and decide what should be done further with useEffect hook help:
const Child = ({color}) => {
useEffect(()=>{
switch (color) {
case "#fff":
console.log('the color is white')
break
case "#000":
console.log('the color is black')
break
default:
console.log(`the color's code is ${color}`)
}
}, [color])
<p style={{"color":color}}>{color}</p>
}
Here you catch the new data value and make a decision whether anything should be done or not. You can call any functions, set up className etc, but the main idea s all these should be based on state / props change. You can also define function in you parent component and then send it to the child component as prop:
const Child = ({func}) => {
func("Hi")
return null
}
const Parent = () => {
const func = (str) => {
console.log(str)
}
return <Child func={func} />
}
Upvotes: 0
Reputation: 582
1- Pass function as props
import React, { useContext, useState, useEffect, useMemo, useRef } from "react";
function Invoice() {
const accordionRef = useRef(null);
const toggleAccordion = () => {
accordionRef.current.click();
}
return (<Modal toggle={toggleAccordion }/>);
}
import React, { useContext, useState, useEffect, useMemo, useRef } from "react";
function Modal({toggle}) {
toggle();
}
}
2- Configure store (Context API or Redux)
checkout this open-sourced repository which shows both ways, see here
Upvotes: 0