M
M
Maksipes2018-07-19 13:28:15
React
Maksipes, 2018-07-19 13:28:15

How to arrange the interaction of React components in an existing project?

To begin with, I will give a very exaggerated example of what is already there, to make it easier to understand what I want to get.
The first component does the input of numbers:

class FirstСomponent extends React.Component {
  render() {
    return <input type="number" onChange={this.props.onChange} />;
  }
}

Their second conclusion:
class SecondСomponent extends React.Component {
  render() {
    return <div>{this.props.data.val}</div>;
  }
}

And there is a shell component that has a state, processes the event, passes data to the child components, i.e. provides the logic of work:
class Main extends React.Component {
  state = { val: 0 };

  onChange = e => {
    this.setState({ val: e.target.value });
  };

  render() {
    return (
      <div>
        <FirstСomponent onChange={this.onChange} />
        <SecondСomponent data={this.state} />
      </div>
    );
  }
}

And all this together is displayed in one place in the document:
const rootElement = document.getElementById("root");
ReactDOM.render(<Main />, rootElement);

As far as I understand, this is a standard scheme for the interaction of components. This is what I already have and it works.
Now I need to embed similar functionality into an already existing site, and the first component should be (conditionally) in the header, and the second in the footer, and not somewhere nearby in one place, so I can embed them as in the example above.
Those. I need to insert FirstСomponent and SecondСomponent separately into an existing page and at the same time somehow make them work together.
Like I don't know.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
davidnum95, 2018-07-19
@maksipes

https://reactjs.org/docs/portals.html

M
maksipes, 2018-07-19
@maksipes

If someone suddenly needs the same thing, here is a good example (not mine)

{
...
  render() {
    const { dateStr } = this.state;

    return (
      <React.Fragment>
          {ReactDOM.createPortal(
            <HeaderContent dateStr={dateStr} />,
            document.getElementById("header")
          )}
          <div>This is the main content</div>
          {ReactDOM.createPortal(
            <Footer text="this is cool footer text" />,
            document.getElementById("footer")
          )}
      </React.Fragment>
    );
  }
}

ReactDOM.render(<MyApp />, document.getElementById("main"));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question