Import ReactJS component from another file?

I am new to React. Want to develop an application using small components in separate files and import them into App.js

I tried, but could not understand what I was doing wrong.

Here is my html:

<!DOCTYPE html> <html> <head> <title>App</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <script src="https://unpkg.com/ react@15.3.2 /dist/react.js"></script> <script src="https://unpkg.com/ react-dom@15.3.2 /dist/react-dom.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> </head> <body> <script type="text/babel" src="js/App.js"></script> </body> </html> 

This is my App.js: (from js / directory)

 import MyComp from 'components/MyComp'; class App extends React.Component { render() { return ( <MyComp /> ) } } ReactDOM.render( <App />, document.body ); 

And this is my MyComp.js (from the js / components / directory)

 class MyComp extends React.Component{ render() { return ( <div> Hello World! </div> ) } } export default MyComp; 

If I try this way, I don’t see anything. If I create the MyComp class in App.js, it works like a charm.

Any suggestion what am I doing wrong?

+15
source share
3 answers

For the most part, what you have should work, but I'm not quite sure why this is not so. I would recommend adding β€œ./” to the import location, but if this is not correct, an error will occur and it will not disappear.

Let me post an even simpler version that I know works:

./index.js:

 import React from 'react'; import ReactDOM from 'react-dom'; import Application from './components/Application' ReactDOM.render(<Application />, document.getElementById('root')); 

./components/Application:

 import React from 'react'; class Application extends React.Component { render() { return ( <div className="App"> My Application! </div> ); } } export default Application; 

It must be all that is needed for this to work.

If you want to shorten the above even further by removing the export line at the bottom, a less traditional approach would define a class like this ...

 export default class Application extends React.Component {...} 
+12
source

The recommended way to develop React applications is to use node, npm, and create-react-app .

create-react-app will make the initial setup of your project all necessary and ready to go. And, among other things, importing components from other modules will work as soon as possible.

0
source

You should add: import React from 'Reaction'; Application class extends React.Component {...

0
source

Source: https://habr.com/ru/post/1269196/


All Articles