Reputation: 57
I am creating a simple web profile using React and am trying separate the Navbar class into separate file.
I would like to have:
navbar.js
//Navbar Component
class Navbar extends React.Component {
render() {
const home = React.createElement('button', {className: 'button1'}, 'Home');
const contact = React.createElement('button', {className: 'button2'}, 'Contact');
return React.createElement('div', null, home, contact);
}
}
export default Navbar;
Along with:
index.js
import Navbar from './navbar.js'
// Creates and renders all individual components
class App extends React.Component {
render() {
return React.createElement(Navbar, null, null);
}
}
// Finalize - Render App which then renders all components
ReactDOM.render(
React.createElement(App, null, null),
document.getElementById('root')
);
However I get the error:
Uncaught SyntaxError: Cannot use import statement outside a module
It only seems to work when both classes are deeclared in same file as follows:
//Navbar Component
class Navbar extends React.Component {
render() {
const home = React.createElement('button', {className: 'button1'}, 'Home');
const contact = React.createElement('button', {className: 'button2'}, 'Contact');
return React.createElement('div', null, home, contact);
}
}
// Creates and renders all individual components
class App extends React.Component {
render() {
return React.createElement(Navbar, null, null);
}
}
// Finalize - Render App which then renders all components
ReactDOM.render(
React.createElement(App, null, null),
document.getElementById('root')
);
Any tips on importing this component?
Upvotes: 1
Views: 874
Reputation: 3487
I believe all you need to do is to add the attribute type="module"
to your <script>
tag in the index.html
file, like below:
<script src="path/to/your/index.js" type="module"></script>
Then, browsers will interpret your inline index.js
code as an ECMAScript module and your import statement should work. More info can be found here (just search for type="module").
Upvotes: 1