Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger a state from another component In Reactjs

Tags:

Hello world I need help with this.

I have a progress bar component and a component where I use the progress bar in it. And another component which supposes to trigger the progress bar.

Examples structure of the APP

  • Home.js
    • Component which has the progress bar (Component 1)
      • Component in Between (Component 2)
        • Component where I want to trigger the progress bar from (Component 3)
  • ProgressBar component (ProgressBar)

https://codesandbox.io/s/optimistic-stallman-rjxi9?file=/src/App.js

This is an example of what exactly I want to achieve and how I imagine it. the code doesn`t work but you will get the idea from the structure of the code.

I want to perform onClick from Component 3 to change the progress Bar state which is located in Component 1 but there is a Component in between as well as the progress bar on its own Component.

Things I tried is passing the function normally to a new function in the component that I want to trigger that action from (Component 3) and pass that function to the button. but it gets an error "Type error this.props.* is not a function"

Thank you in advance

like image 226
Dev01 Avatar asked Dec 20 '20 22:12

Dev01


1 Answers

You need to make Component2 (C2) and Component3 (C3) to be children of Component1, and pass handleProgress as a prop to Component2 and Component3 like here https://codesandbox.io/s/blue-lake-6mx7o?fontsize=14&hidenavigation=1&theme=dark

For now, you created a function handleProgress in C1, but you never passed it to C2 and C3.

To pass it to C2 and C3, you need to remove them from App component, and move them to C1.

like image 163
IvanD Avatar answered Sep 30 '22 14:09

IvanD