Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a React app have components in different JS files without a build system?

React examples use gulp, Grunt, or npm and Browserify or Webpack. In the code below I have a React app without those, and I am just wondering if this last step is possible.

An HTML page that pulls in React, babel-browser, and one JavaScript file:

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body>
  <script src="https://unpkg.com/[email protected]/dist/react.min.js"></script>
  <script src="https://unpkg.com/[email protected]/dist/react-dom.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.25/browser.min.js"></script>
  <script type="text/babel" src="js/App.js"></script>
</body>
</html>

Here is App.js

'use strict';
var {
  Component
} = React;
class Hdr extends Component {
  render() {
    return (<header className="container">Header</header>);
  }
};

class App extends Component {
  render() {
    return (
      <main>
        <Hdr />
      </main>
    );
  }
};
ReactDOM.render(<App />, document.body);

The App component pulls in the Hdr component. Here is the question: how can I put the Hdr in a separate JS file? I tried it, and App cannot find Hdr.

Here is a working demo.

like image 207
getsetbro Avatar asked Oct 12 '15 02:10

getsetbro


People also ask

Should React components be in separate files?

React is all about re-using code, and it is recommended to split your components into separate files. To do that, create a new file with a . js file extension and put the code inside it: Note that the filename must start with an uppercase character.

Does React have built in components?

React and Web Components are built to solve different problems. Web Components provide strong encapsulation for reusable components, while React provides a declarative library that keeps the DOM in sync with your data.

Can we create ReactJs app without Nodejs and JSX?

Start by creating a simple HTML web page. You can also use an existing HTML website. Insert the React and React-dom script tags in the head section of your HTML page.


1 Answers

http://plnkr.co/edit/Pw75IIuonyz9UlBhvWo5?p=preview

You just have to do

window.Hdr = Hdr

And it will work.

Edit : Based on Joshua's comment

window.__MyApp__ = {
   // a lot of app props
}
window.__MyApp__.Hdr = Hdr
like image 110
Bhargav Ponnapalli Avatar answered Sep 23 '22 04:09

Bhargav Ponnapalli