2

I'm porting a small script over to React. It's a simple country-region-selector plugin that ties together a country dropdown and a region dropdown, so the latter always shows the relevant regions for the selected country. See: https://github.com/benkeen/country-region-selector

Thing is, I can't quite fathom the best way to componentize this using React. I need the two key elements (the country dropdown and the region dropdown) to be completely independent, so a user can choose exactly where the two dropdowns appear in the DOM + the surrounding markup. But I want all the inner-workings (i.e. how the two components are tied together) to be hidden from view. I was thinking maybe something like this...

<CountryRegions>
   <span>arbitrary markup here</span>
   <CountryDropdown />
   <p>
       <RegionDropdown />
   </p>
</CountryRegions>

... but I'm hazy on how the actual implementation of that would work. Any ideas / better suggestions? Hope this question is clear.

4
  • Are you saying you want your country selector to be two React components that might both exist within HTML (ie two ReactDOM.render() calls), or the whole app is React and you want the components to exist anywhere in the app? Commented May 17, 2016 at 18:47
  • Not sure I quite follow... basically I don't want users to have to wire the two dropdowns together. e.g. maintain the selected state of the country dropdown + pass that value to the region dropdown. Instead, I'd like to allow users to just include that single <CountryRegions /> component, containing the two dropdowns in whatever markup they want. That'd make the component really easy to "drop-in" into a React application. Commented May 17, 2016 at 19:06
  • Ok so it sounds like the components exist in the same React application, I just wasn't sure if you were saying you wanted React elements mixed in a traditional HTML page within separate HTML containers. Commented May 17, 2016 at 19:10
  • Ah, gotcha! Yeah, same app - all in React. Commented May 17, 2016 at 19:24

1 Answer 1

2

You can share something between components using context. Basically CountryRegions component will provide a context that every child can use.

CountryDropdown and RegionDropdown can use the provided context as long as they are child of CountryRegions component, no matter how deeply nested.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, thanks nvartolomei. Yeah, that looks like it'll fit the bill!

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.