K
K
Ken Jee2017-01-19 10:54:41
JavaScript
Ken Jee, 2017-01-19 10:54:41

How to connect a component from another file in ReactJS?

Dear React experts! Can you tell me how to properly organize the connection and use of a component that is stored in a separate file? In the example below, I need to use the Header component inside the main.js file, which is stored in the componets/header.js
Index.html file:

<!DOCTYPE html>
<html lang="ru">
<head>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="/css/normalize.css">


  <link rel="stylesheet" href="https://unpkg.com/[email protected]/build/pure.css">
  <link rel="stylesheet" href="/css/style.css">

  <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://unpkg.com/[email protected]/babel.js"></script>

       <script src="/js/main.js" type="text/babel"></script>

  <title>Тайтл</title>

</head>
<body>

<div id="layout"></div>

</body>
</html>

/js/components/header.js:
"use strict";

class Header extends React.Component {
    render() {
        return <header>This is Header</header>;
    }
}

/js/main.js:
'use strict';

import Header from 'components/header';

ReactDOM.render(
    <Header />,
    document.getElementById( 'layout' )
);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2017-01-19
@Machez

You need to bundle with Wepback / Browserify etc. Require / import won't work even if text/babel is specified.
A bit from SO:
stackoverflow.com/a/36698789/1916578 (why require/import doesn't work)
stackoverflow.com/a/20578692/1916578 (just in case you're not running a local server - there's info on the error here and whats up with do these) + it is easy to raise a local server using http-server

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question