1

I try to include a script from Leaflet in a React element, and because it contains a <script>code</script> it raises an error:

var Carte = React.createClass({
render: function() {
var styl = {
    height: 400,
    width: 800,
    position: 'relative',
    margin: 'auto'
   }
    return (
        <div id="lguit">
            <div id="map" style={styl}></div>
                <script>
                    document.querySelector("#lat").val = lat;
                    document.querySelector("#lon").val = lon;
                    map = L.map("map", {
                        center: [
                            lat,
                            lon
                            ],
                        minZoom: 5,
                        zoom: 5
                    });
                    L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {
                        attribution: "OpenStreetMap"
                    }).addTo(map);

                </script>
        </div>
    );
}
});

I get this error:

Uncaught Error: Parse Error: Line 26: Unexpected token :
at http://localhost:8000/static/js/main-react.jsx?v=c3affc6ee4977467587b88895c12cccc:26:undefined

center: [
     ^

Edit: Tried this:

<script dangerouslySetInnerHTML={{__html: 'document.querySelector("#lat").val=lat;document.querySelector("#lon").val=lon;map = L.map("map", {center: [lat,lon],minZoom: 5,zoom: 5});L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {attribution: "OpenStreetMap"}).addTo(map);'}} />

and the script dident execute, but will work after the DOM finishs loading (if i execute it alone in the console)

2
  • 1
    You should probably just take out the script tag, and move the logic into componentDidMount. Commented Sep 8, 2015 at 23:03
  • i think this is the solution, because even after using dangerouslySetInnerHTML the script stays idle and dont execute Commented Sep 8, 2015 at 23:06

1 Answer 1

0

It seems that the right way is to use componentDidMount

var Carte = React.createClass({
    render: function() {
    var styl = {
    height: 400,
    width: 800,
    position: 'relative',
    margin: 'auto'
    }
    return (
        <div id="lguit">
            <div id="map" style={styl}></div>
        </div>
    );
},
componentDidMount: function() {
    document.querySelector("#lat").val=lat;
    document.querySelector("#lon").val=lon;
    map = L.map("map", {center: [lat,lon],minZoom: 5,zoom: 5});
    L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", {attribution: "OpenStreetMap"}).addTo(map)};
}
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.