Update React State from Component Props

ReactJS state and prop data model is so flexible that I cannot fathom how to solve information system problems otherwise, and I keep reminding this to myself everyday I use it. Recently I came across a situation where I needed to re-use a component, passing it props from a parent component, and having the component (or global) state updated on-the-fly.

Let me briefly describe the situation I am referring to. Let's say I am using the official Stripe Checkout component to for my next SaaS application. I want to have a re-usable component so I can create a multi-tier pricing subscription plan.

The Stripe Checkout component will therefore look like this:

Notice that this Stripe component can be used by a parent component so I can generate 3 different pricing plans. This is simply achieved by calling this component three times and using the appropriate props as follows:
Now if I want to be able to set the application state for the planPrice, so other components are aware that what the chosen price is, can be simply achieved by binding an onClick function call to the Button component inside the Stripe Checkout component:

This is a very nifty trick that most ReactJS developers should be aware of. This allows us to re-use our components without losing control of the component state.
Post a Comment