How to store a react element in a variable and render it elsewhere?

Viewed 87

I have a component ComponentCreator which creates a state and another component component.

const ComponentCreator = () => {

  const [value, setValue] = useState('');

  const component = <input
      value={value}
      onChange={(e) => setValue(e.target.value)}
    />

  return component;

}

export default function App() {
  return (
    <>
    <ComponentCreator />
    </>
  );
}

This works fine.

Now what I want is to somehow share the component between other components. It is important that the state

const [value, setValue] = useState('');

stays inside the ComponentCreator and it is not lifted up.

So how could I render the component to lets say the App component ?

I tried this:

const ComponentCreator = ({setC}) => {

  const [value, setValue] = useState('');

  const component = <input
      value={value}
      onChange={(e) => setValue(e.target.value)}
    />

  useEffect(() => {
    setC(component);
  }, [])

  return component;

}

export default function App() {

  const [c, setC] = useState(null);
  return (
    <>
    {c}
    <ComponentCreator setC={setC} />
    </>
  );
}

but it is not working. I am getting a really weird behavior where I can only type one letter in the input component of App but still working fine inside ComponentCreator.

How can I achieve this ?

[EDIT]

Answering to comments:

The reason I want this is the following.

I want a component to trigger a method createDialogWithConent with "fire and forget" approach.

const [value, setValue] = useState('');

  const component = <input
      value={value}
      onChange={(e) => setValue(e.target.value)}
    />

...
<button onClick={ () => createDialogWithContent({content: component}) } ... />
...

and the the dialog would render the content

const DialogWrapper = () => {
   const { content: component } = useDialogContent();

   return <Dialog>
       {component}
      <Dialog />

So the component which triggers the createDialogWithContent has access to [value, setValue] so it can use it in a later time, and also this state can be changed when the dialog pops up.

0 Answers
Related