React - Parent Class use Child function

I have a Parent class where I am rendering components depending on the an index.
In My Parent component I also have a stepper that works similar than some pagination.

the currentComponent has its own submit function and I would like to call this function when navigating from the stepper. How can I call the child components function within the Parent ?

class Parent extends Component {
    render() {
        let curentComp;

        switch (this.state.currentIndex) {
            case 1:
                curentComp = <Component1 />;
                break;
            case 2:
                curentComp = <Component2 />;
        }

        return (
            <div>
                <Stepper currentIndex={this.state.currentNavIndex} navItems={navItems} small={this.state.small} />
                {curentComp}
            </div>
        );
    }
}

You don’t. Put the the function in the parent component and pass that function to the child.

Yeah but the submit function of each Child is very different and takes different parameters

React has a strict parent-child only data flow, to achieve what you want, you need to have the “choosing” logic in the parent function.

For example you can pass all arguments, and in the parent simply “choose” what to do:

function myFn(data) {
 if condition1 do stuff1
if condition2 do stuff2

[..ecc]
}

Or you can have it accepting function directly as param.

function myFn(cb) {
 cb();
}

myFn(() => console.log("foo"));

Hope it helps :slight_smile:

Why do you think it matters that that function is defined in the child? Practically, it should make no difference if you pass the function in as a prop from the parent or you define it within the child. And in this case you have to do that, there’s no choice: these components are basically just functions, and this is how functions work – you can’t get at the stuff inside the function from outside it. If you want to affect something in the parent, that’s the job of the parent, if its state needs to be altered it needs to provide the functionality to do that. You’re mixing up responsibilities by trying to make a completely different function (the child component) reach into another function (the parent function) to try to alter it.

ok thanks for your reply. I also heard about passing data from child to parent by using a callback and states

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.