1252748
1252748

Reputation: 15372

Where should I put data and methods within nested components?

I'm trying to understand how I can do the following flow in React

page load
  ajaxA()
    -return dataA
      -render dropdown HTML
      -ajaxB(dataA)
        -return dataB
          -render chart HTML


handleDropdownChange()
  -ajaxB()
    -return dataB
      -render chart HTML

I have it split out into two components

Should ParentApp contain all methods for updating the charts and data related to child components, passing both in as props, eg:

handleControlChange (event) {

  this.setState(selectedOption: event.target.value)
},
render () {
  return (
    <ParentApp>
      <Controls
        handleControlChange={this.handleControlChange} />
      <Chart />
    </ParentApp>
  )
}

or should that functionality live within the Controls component? The second way seems more reasonable to me but since Controls and Chart are siblings I'm not sure how I can pass data to Chart when there is a change within`Controls. As I understand it data only flows from parents to children in React. It seems like ParentApp would soon contain basically all the methods needed by its children components which kind of seems it goes against keeping components modular.

Where should I store my data and my methods to interact with it?

Upvotes: 0

Views: 46

Answers (1)

niceman
niceman

Reputation: 2673

In principle React only lift the state up when this state must be shared between siblings and/or parent, when a child component doesn't need to send its state to parent or siblings it can have its own state and no lifting up is needed.

But practically speaking most apps will have state in central place at parent component, there are even libraries for central states like Redux , that being said we didn't lose modularity in any way because state is only part of the story, for example spliting the app into components will give you modularity in rendering, also because child components takes props you can reuse the same component in multiple places with different props to control its appearance almost the same way you change the appearance of an <a> link by just applying a class.

Upvotes: 1

Related Questions