Reputation: 7534
I am currently trying to adapt a React component so that it can be called from a regular non-React script. The particular component I am trying to get working is 'react-responsive-carousel'.
The HTML:
<div id="slides" style="display: none">
<div>
<img src="http://lorempixel.com/output/cats-q-c-640-480-1.jpg" />
<p className="legend">Legend 1</p>
</div>
<div>
<img src="http://lorempixel.com/output/cats-q-c-640-480-2.jpg" />
<p className="legend">Legend 2</p>
</div>
<div>
<div id="root"></div>
Then in the 'react adaptor':
import "react-responsive-carousel/lib/styles/carousel.min.css";
import { Carousel } from "react-responsive-carousel";
function renderCarousel(targetElementId, html) {
const App = function() {
return <Carousel>
<div dangerouslySetInnerHTML={{ __html: html }} />
</Carousel>;
};
render(<App />, document.getElementById(targetElementId));
}
Then the calling code that would be used by the non-React script:
renderCarousel("root", document.getElementById("slides").innerHTML);
The issue with this is that an extra 'div' is introduced which breaks the carousel's behaviour. Is there any way I can pass this HTML in such a way the inner HTML of div with id 'slides' is directly under the Carousel component or maybe there is another way of achieving the intended goal?
Note, this needs to work from an ES5 calling context.
Upvotes: 3
Views: 3425
Reputation: 243
I understood the issue, so the html you have there, would be all the slides right ?
What I would do is to pass the slides to the function as an array:
renderCarousel(targetElementId, slides)
so you can do something like:
function renderCarousel(targetElementId, slides=[]) {
const App = function() {
return <Carousel>
{slides.map(html => <div dangerouslySetInnerHTML={{ __html: html }} />)}
</Carousel>;
};
render(<App />, document.getElementById(targetElementId));
}
it should work with something like:
const slides = Array.from(document.getElementById("slides").children)
renderCarousel("root", slides.map(slide=> slide.innerHTML))
Let me know how it goes !
Upvotes: 3