M
M
Maksipes2018-09-10 23:38:52
React
Maksipes, 2018-09-10 23:38:52

What is the correct way to use a React component multiple times on a page?

Usually, React examples show how the created component renders once to one node, usually with id="root".
I have a different task - I need to insert the page into the html several times, in different places, the same React component, with different parameters.
I'm interested in the right example of how to do it.
So far I have done this (example simplified to the limit):
https://codesandbox.io/embed/l21j84vjmq
html

<div class="root" feed='{"name":"Maks", "age":33}'></div>
<div class="root" feed='{"name":"Petr", "age":22}'></div>
<div class="root" feed='{"name":"Boxy", "age":27}'></div>

point of entry
const elements = document.getElementsByClassName("root");

for (var i = 0; i < elements.length; i++) {
  const feed = elements[i].getAttribute("feed");
  render(<ShowSomeInfo key={i} feed={feed} />, elements[i]);
}

jsx component
class ShowSomeInfo extends React.Component {
  constructor(props) {
    super(props);
    const user = JSON.parse(this.props.feed);
    this.state = { name: user.name, age: user.age };
  }

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

  render() {
    return (
      <div>
        <h2>{this.state.name}</h2>
        <h2>{this.state.age}</h2>
        <input type="number" value={this.state.age} onChange={this.onChange} />
      </div>
    );
  }
}

In this case, everything works as it should, but I'm worried about whether such a system will slow down; How is this generally correct and accepted to do so?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question