Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import ReactJS component from another file?

I'm new to React. Want to develop an app using little components in separate files and import them to my App.js

I tried but not be able to figure out what I'm 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/[email protected]/dist/react.js"></script>     <script src="https://unpkg.com/[email protected]/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 js/components/ directory)

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

If I try this way I see nothing. Whereas if I create MyComp class in App.js it works like a charm.

Any suggestion what am I doing wrong?

like image 559
Omer Avatar asked Jun 25 '17 08:06

Omer


People also ask

How do I export and import components in react?

Use named exports to export a component in React, e.g. export function Button() {} . The exported component can be imported by using a named import as import {Button} from './another-file. js' . You can use as many named exports as necessary in a file.


1 Answers

For the most part, what you have should work, but I'm not quite sure why it doesn't. I would recommend adding "./" to the import location, but if that was incorrect, it would error out and not silently go away.

Allow me to post an even simpler version which I know does work:

./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; 

This should be everything needed to make it work.

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

export default class Application extends React.Component {...} 
like image 60
HoldOffHunger Avatar answered Sep 24 '22 03:09

HoldOffHunger