I have two components:
The parent is class component and child is functional component. What is best practice to call child methods from the parent component?
The goal of these components is to be able to load svg file dynamically.
Parent component:
class UnitMonitor extends PureComponent {
constructor() {
super();
}
state = {
img: null,
};
onChangeShcema = schemaID => {
axios.get("/api/schemata/get-schemata-nodes/" + schemaID).then(response => {
let path = response.data["0"]["file"];
// call loadFile function of child component is needed
});
render() {
return (
<Row type="flex" className="">
<Col span={25}>
<SvgViewer />
</Col>
</Row>
);
}
};
Child Component:
const SvgViewer = () => {
const loadFile = path => {
let svgFile = require("./images/" + path);
const svg = document.querySelector("#svgobject");
svg.setAttribute("data", svgFile);
};
return (
<div className="unit-schema-container1">
<object id="svgobject" type="image/svg+xml" data={null}></object>
</div>
);
};
export default SvgViewer;
To pass data from child to parent component in React: Pass a function as a prop to the Child component. Call the function in the Child component and pass the data as arguments. Access the data in the function in the Parent .
In React we can access the child's state using Refs. we will assign a Refs for the child component in the parent component. then using Refs we can access the child's state. Creating Refs Refs are created using React.
In React it is not a good idea to try to run a child method on the parent since it is mainly a sign of a bad design. Since you want to run the SVG dynamically, you could pass a prop with the path or what you need in order to load it dynamically. However, if you are adamant in running the method on the parent check out this post on how to do it.
Define all your function in parent component and pass that as props to child component.
Try this
class UnitMonitor extends PureComponent {
constructor() {
super();
}
state = {
img: null,
};
onChangeShcema = schemaID => {
axios.get("/api/schemata/get-schemata-nodes/" + schemaID).then(response => {
let path = response.data["0"]["file"];
this.setState({img: path});
// call loadFile function of child component is needed
});
render() {
return (
<Row type="flex" className="">
<Col span={25}>
<SvgViewer onChangeShcema ={this.onChangeShcema} image={this.state.img} />
</Col>
</Row>
);
}
};
Access like this in child component
onChange={props.onChangeShcema}
or onClick={props.onChangeShcema}
img={props.image}
Use temporary props. For example click count. Handle click count in useEffect hooks methods When props.count is changed, call function )
in your child component use this code segment:
useEffect(() =>Call your function is here, [props.count ]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With