inzimam inzimam - 1 month ago 11
Javascript Question

returning two components in react aren't working

I tried Hello world example by returning Hello and world from two other components which worked but here in this code I'm not able to return Menubar component whereas Map components works when I only return Map.

App.js

import React from 'react';
import ReactDOM from 'react-dom';
import Map from './components/Map'
import Menubar from './components/Menubar'

var App = React.createClass({

render: function(){

const location = {
lat: 33.980397,
lng: 71.427217
}
return(
<div style = {{height: '100%' , width:'100%'}}>

<div><Menubar /></div>

<div><Map center={location}/></div>

</div>
);
}
}
);
ReactDOM.render(<App />, document.getElementById('app'));


Menubar.js

import React from 'react';

var Menubar = React.createClass({
render: function(){

return (<div>Hello</div>);

}
});

export default Menubar


Map.js

import React from 'react';
import { GoogleMapLoader, GoogleMap } from 'react-google-maps';


var Map = React.createClass({

render: function(){
const mapContainer = <div style={{height: '100%', width:'100%'}}></div>

return(

<GoogleMapLoader
containerElement = { mapContainer }
googleMapElement = {
<GoogleMap
ref = {(map) => {
if (this.state.map != null)
return
this.setstate({
map: map
})
}}
defaultZoom={15}
defaultCenter={this.props.center}

options={{streetViewControl: false, mapTypeControl: false}}>
</GoogleMap>
}/>

)
}
}

);
export default Map


index.html

<html>
<head>
<meta charset="UTF-8">
<meta name=viewport content="width=device-width, initial-scale=1">
<title>VizAp</title>


<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-bootstrap/0.29.4/react-bootstrap.min.js"></script>
</head>
<body>
<div id='app'></div>
<script src="index.js"></script>
</body>
</html>


It should output Hello and Google map. Although Map component is returning when I remove Menubar tag from App.js.

These are the errors I'm getting from console:


  • TypeError: undefined is not an object (evaluating
    'u["default"].createClass') (Solved)

  • TypeError: null is not an object (evaluating '_this.state.map') (Solved)


Answer

You need to set your initial state in Map.js prior to referencing this.state in your render method. To do this you should use the following:

getInitialState: function() {
    return {
        map: SomeValueHere
    }
},
render: ...

It looks like there is a missing variable called "map" which should be assigned to this.state.map if this.state.map is null.

Secondly I would remove the "Default" from your export statements. This may be causing this : TypeError: undefined is not an object (evaluating 'u["default"].createClass')

This explains in detail how to use exports. You will only ever have one "Default" per module. But you may have many exports.

There may be other issues here, this is just the first thing I have noticed.