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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With