0

I need to triger child function inside parent component? I am using React

Parent component ->

selectedColors = (colors) => { 
   // need to props colors and trigger child function.
  };


    <Field
      id="primary-color"
      name="theme.primaryColor"
      component={ButtonColorPicker} 
     />

Child component is ButtonColorPicker

ButtonColorPicker component ->

  handleChange = (color) => {
    console.log("here i need props value from PARENT", color);
    this.props.input.onChange(color.hex);
  };

 <SketchPicker color={input.value} onChange={this.handleChange} />

import { SketchPicker } from "react-color";

SketchPicker is just plugin for changing colors.

I need from parent component to trigger handleChange function.

3
  • 2
    Put the handle function into your parent component an pass it to your child as a prop Commented Mar 6, 2022 at 19:34
  • I can;t because in child component i have some properties which i don;t have in parent Commented Mar 6, 2022 at 23:57
  • that's okay, just pass the function as a said, then you can call it inside your child component using the values you need from it Commented Mar 7, 2022 at 15:53

1 Answer 1

1

You can try this.

First, create a state that will determine when the function will be triggered.

const [trigger, setTrigger] = useState(false)

Now you pass trigger to your children component, and inside it you can create a useEffect with trigger inside your dependency array that will call your function.

useEffect(() => {
    // children function to be triggered is here.
}, [trigger])

Now, everytime you change your trigger state on parent component, the children function will be triggered.

On your parent component, you can do something like

selectedColors = (colors) => {
    setTrigger(true)

    // whatever you want.

    setTrigger(false)        
}
Sign up to request clarification or add additional context in comments.

5 Comments

You could technically just pass the reference to the function as well.
I think the question title is missleading. If I understood it correctly, he wants to trigger a function from the children component, from an action inside parent.
Right. So the function actually lives in the parent context and is passed down to the child through props so both can call the function.
Oh ok, now I get what you are talking. I guess this is a better solution if you want both components to have control over the function trigger.
Ahhh friend, i am using class components :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.