OokerO
Denoβ€’3y agoβ€’
6 replies
Ooker

How to send data from a child component to its sibling?

I want create an app with two forms, each form in its own component. Users type in form 1, then the data will be passed to component 2. In there it will join the data of what they type in form 2. How can I do this?

Below is the code on my machine, taken from the answer from the same question in Stack Overflow. It works when using React on Stackblitz but I don't get why it's not in my machine:

index.jsx

import Form1 from "../islands/Form1.tsx";
import Form2 from "../islands/Form2.tsx";
import { Form1Provider } from "../islands/Context.tsx";

function App() {
  return (
    <Form1Provider>
      <Form1 />
      <Form2 />
    </Form1Provider>
  );
}

Context.js

import { createContext } from 'preact'
import { useContext, useState } from "preact/hooks";

export const Form1Context = createContext(null);

export function Form1Provider({ children }) {
  const form1State = useState('Form 1 placeholder');
  return (
    <Form1Context.Provider value={form1State}>{children}</Form1Context.Provider>
  );
}

Form1.jsx

import { useContext, useState } from "preact/hooks";
import { Form1Context } from './Context.tsx';

export default function Form1() {
  const [form1Data, setForm1Data] = useContext(Form1Context)
    
  return (
    <textarea 
    value = {form1Data} 
    onInput={(event) => setForm1Data(event.target.value)}
    />
  );
}

Form2.jsx

import { useContext, useState } from "preact/hooks";
import { Form1Context } from './Context.tsx';

export default function Form2() {
  const [form1Data, setForm1Data] = useContext(Form1Context)
  const [form2Data, setForm2Data] = useState('Form 2 placeholder')
    
  return (
    <>
        <textarea 
            value = {form2Data} 
            onInput={(event) => setForm2Data(event.target.value)}
        />
        <p>The value is {form1Data} + {form2Data}</p>
    </>
  );
}

The app compiles fine, but the actual result is empty.
Stack Overflow
I want create an app with two forms, each form in its own component. Users type in form 1, then the data will be passed to component 2. In there it will join the data of what they type in form 2. H...
How to send data from a child component to its sibling?
Was this page helpful?