Skip to content Skip to sidebar Skip to footer

Sharing Data Between Components In React

I'm developing an app using Meteor and React as view engine Consider this diagram: React hide component from another example I need to change C2 component state when C4 button clic

Solution 1:

You can use any publish/subscribe events library and then make your components listen to any event you need.

For example:

importReactfrom'react'import'events'from'eventPublishSubscribeLibrary'classComponent2extendsReact.Component {
  constructor (props) {
    super(props)
    this.toggleVisibility = this.toogleVisibility.bind(this)
    this.state = {
      visible = true
    }
  }
  componentDidMount () {
    events.subscribe('clicked-button', this.toogleVisibility)
  }
  toogleVisibility () {
    this.setState({
      visible: !this.state.visible
    })
  }
  render () {
    return visible && (
      <div>content</div>
    )
  }
}

constComponent4 = () => (
  <buttononClick={events.publish('clicked-button')}>Toggle Visibility</button>
)

You can find in this post by davidwalsh a simple implementation for a Pub/Sub JavaScript Object. Or you can search in npm for some other library.

the "right" way

This is the most simple implementation I can think of and for small projects it is a quick an easy solution that should work.

Anyway, as far as the project will grow a bit you will start to have a lot of actions/reactions between your components. With every new component you'll add it'll get more complicated to track all of these relations between all your components. Here is where it comes handy to have the global state of your application stored in one single place, and that is one of the three principles that redux is based on: the single source of truth.

Solution 2:

I think it's perfect time for you to introduce some state to your app. Try Redux, it's awesome.

Post a Comment for "Sharing Data Between Components In React"