2

I want to create a React.JS component which can be rendered in multiple places using the classname of div elements instead of an id.

The regular way to render a component is this:

React.render(<Component/>, document.getElementById('id'))

while I wonder if it' possible to do this:

React.render(<Component/>, document.getElementsByClassName)?

2 Answers 2

7

React.render takes a single DOM element. If you want to render it more than once, simply iterate over the nodes.

function renderToElements(toRender, elements) {
  for (var i = 0; i < elements.length; i++) {
    React.render(toRender, elements[i]);
  }
}

renderToElements(..., document.getElementsByClassName("className"));
Sign up to request clarification or add additional context in comments.

Comments

0

Just adding onto @Michelle Tilley's answer, I really wanted to do this technique while grabbing a dataset from each element to pass in as a prop. The key was to pass the ComponentName without quotes or brackets and then to createElement with it :

let elems = document.getElementsByClassName("class_name");

function renderToElements(toRender, elements, dataset) {
  for (var i = 0; i < elements.length; i++) {
    let passId = elements[i].dataset[dataset];
    let renderEl = React.createElement(toRender, {id: passId})
    ReactDOM.render(renderEl, elements[i]);
  }
}

renderToElements(ComponentName, elems, 'id')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.