Search code examples
javascriptreactjsopenlayers

OpenLayers React JSX Component


I have the following React Component that uses Openlayers and it works as expected:

import React from 'react';
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { Card } from 'material-ui'
import CardBanner from './CardBanner'


// Open Layers Imports
import ol from 'openlayers';
import 'ol/ol.css';


class WebMapService extends React.Component {
    constructor(props) {
        super(props)

        this.map = {};
    }


    componentDidMount() {

        this.map = new ol.Map({
            layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM()
                })
            ],
            target: 'map',
            view: new ol.View({
                center: [0, 0],
                zoom: 2
            })
        });

        // this.map.updateSize();
        // this.map.render();
        // this.map.redraw();
    }


    render() {
        //if(this.props.contentRender) {      // Conditional Rendering
        return (
            <div>
                <Card id="WebMapService" className="cardContainerFullScreen">


                    <div id="map" className="map" ref="olmap"></div>


                </Card>
            </div>
        )
        //}else{return false}
    }
}



WebMapService.propTypes = {
    contentRender: PropTypes.bool
};

const mapStateToProps = (state) => {
    return {
        contentRender: state.setWMSComponentStatus.setWMSComponentStatusState
    }
}

export default connect(mapStateToProps)(WebMapService);

When I uncomment the following lines from render() it fails to load:

//if(this.props.contentRender) {

//}else{return false}

Purpose of these 2 lines. This React Component is loaded at the point a dashboard is loaded. The component then listens to Redux for a "true" render and then the component renders.

Is there a way to therefore refresh or reload load openlayers in a situation like this. I've tried a few ideas in componentDidMount() like .render() etc.

Note: if there's a better way to load the component on the fly I'd be interested.

thanks


Solution

  • Your render method needs to always return some valid html markup or React components or null. You should change your code to

    if(this.props.contentRender) {
    ...
    }else{return null} 
    

    or better

    if(this.props.contentRender) {
    ...
    }else{return <div> Loading... </div>}