Reputation: 6258
I'm using WebPack and ES6, so I can't use module.exports
and have to use export default
. I have a library like this:
// helloworld.js
import React from 'react';
class HelloWorld extends React.Component {
test() {
alert("TEST FROM test()");
}
render() {
alert("TEST");
return (
<p>Hello, world!</p>
);
}
}
// THIS WORKS WHEN I REQUIRE THIS MODULE
// var thing = new HelloWorld();
// thing.test();
export default HelloWorld;
The commented out portions work when I var helloworld = require('helloworld.js');
, but I can't figure out how to initialize and use this object outside where I require this.
None of these attempts work. How do I initialize this object and use it?
// hello_world.test();
// hello_world.HelloWorld.test();
// var thing = new hello_world();
// var thing = new hello_world.HelloWorld();
My main reason is because I need the component in a route using ReactRouter like this and none of these attempts work.
I tried this (bellow) and this tells me to check the render method...
ReactDOM.render(
(<BrowserRouter>
<Switch>
<Route exact path="/helloworld" component={hello_world}/>
</Switch>
</BrowserRouter>)
This (bellow) renders a BLANK PAGE!!!!
ReactDOM.render(
(<BrowserRouter>
<Switch>
<Route exact path="/helloworld" component={hello_world.HelloWorld}/>
</Switch>
</BrowserRouter>)
I'm out of ideas. This does not help. Neither does this. Could please someone lend me some pointers?
EDIT:
Solution was simply to add default
at the end of require (var hello_world = require('./helloworld.js').default;
). This works to use this in the route like: <Route exact path="/helloworld" component={hello_world}/>
.
If you were to use this outside the scope, you would do:
var thing = new hello_world();
thing.test();
Working solution:
var hello_world = require('./hello_world.js').default; // Must add default.
// Using it outside a route, with a class method called test().
var thing = new hello_world();
thing.test();
// Using it in a router (ReactRouter with Switch).
ReactDOM.render(
(<BrowserRouter>
<Switch>
<Route exact path="/helloworld" component={hello_world}/>
</Switch>
</BrowserRouter>)
, document.getElementById("root"));
Upvotes: 0
Views: 977
Reputation: 845
var helloworld = require('helloworld.js').default
is working for me.
Can you check this?
Please guide me if I'm doing wrong here.
Upvotes: 1
Reputation: 15404
You should be able to use the component in a regular jsx file like this:
var HelloWorld = require('path/to/HelloWorld.jsx');
...
<div>
<HelloWorld></HelloWorld>
</div>
Or in a react-router component, with the same require statement like this:
var HelloWorld = require('path/to/HelloWorld.jsx');
....
<Route exact path="/helloworld" component={HelloWorld}/>
Upvotes: 1