Siddharth Siddharth - 3 months ago 11
React JSX Question

Passing Data to Independent Component React

I have this

HomeContainer
component,
Home
component and this
Header
component.


  1. HomeContainer
    contains the
    state of city
    and
    <Home city={this.props.city} />

  2. Home
    contains stateless function and contains JSX. so via
    this.props
    i can access
    HomeContainer's city



Problem - I want to send the data to
Header
so that i can update the city in header whenever someone inputs something in the input field

I think The
Main
component has access to child components but the
Main
component is called via routes so i am not able to figure this out.

Thanks

enter image description here

Answer

You have a jsx structure similar to:

<Main>
  <Header />
  <HomeContainer />
</Main>

Since the city property is to be used by both <Header /> and <HomeContainer />, then it shouldn't be defined in <HomeContainer />

city should instead be defined as a state in <Main /> and passed down to both <Header /> and <HomeContainer />

This implies that you also define the callback to changeCity() in <Main /> and pass it down to <HomeContainer /> as a prop.

This way, both <Header /> and </HomeContainer> will be updated with changes to the city attribute