cjm2671
cjm2671

Reputation: 19456

How do I pass things between components on the same level?

I've got a React app of the form:

<App>
  <ParentComponent>
    <FormComponent>
    <AnotherComponent>
  </ParentComponent>
</App>

I want to be able to update some state values of <FormComponent> by clicking on elements in <AnotherComponent>.

I don't want to place them inside each other, but keep them side-by-side. I don't want to lift up <FormComponent> state as it's nicely encapsulated.

What's the best way to achieve this? Can I do it with just react or do I need RxJS/something else?

Upvotes: 3

Views: 1380

Answers (3)

Avik
Avik

Reputation: 817

Apart from the ways mentioned above you can pass down a function as prop from the Parent component to AnotherComponent. And when clicking any element in Another component, pass the intended value in that function, which will in turn be transferred to ParentComponent. And you can then pass the value as props to the FormComponent from the ParentComponent. You can check this example for better understanding https://react-m9skpu.stackblitz.io

Upvotes: 0

Dennis Vash
Dennis Vash

Reputation: 53874

The data in React Flows Down.

If you don't want to lift the state up, what's left is Context API or any state management library like Redux and MobX (both implement Context API with different strategy).

But still, the state is "above" FormComponent (you still lifting state up).

const Context = React.createContext();

const ParentComponent = () => {
  const contextState = useState(DEFAULT_STATE);
  return (
    <Context.Provider value={contextState}>
      <FormComponent />
      <AnotherComponent />
    </Context.Provider>
  );
};

const FormComponent = () => {
  const [, setState] = useContext(Context);
  // use setState
};

const AnotherComponent = () => {
  const [state] = useContext(Context);
  // valid state updated from FormComponent
};

Upvotes: 4

wpp
wpp

Reputation: 7303

As far as I can tell the "right thing" to do in these instances is move the state up one level, into your Parent component.

If you have a look at the Intro to React:

To collect data from multiple children, or to have two child components communicate with each other, you need to declare the shared state in their parent component instead.

"Lifting state up" is a common thing in React applications and doesn't require introducing a state management solution like Redux or RxJS.

Upvotes: 0

Related Questions