How to have react app in the HTML without npm start or similar commands - reactjs

I'm kinda new to ReactJS and don't even know if it's possible but I want my react app to be working in the browser from the .html file. without the need for calling the server and have it, working, only that way. ( I don't mind having a server to serve it obviously) just need to be able to have by calling the .html file
the public/index.html file:
<head>
<meta charset="utf-8">
<script src="/my_library/my_library.min.js"></script> <!-- needed for the project in the same folder the index.html is -->
<title>Demo</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start`.
To create a production bundle, use `npm run build`.
-->
</body>
</html>
the index.js (in src folder):
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
React.createElement(App),
document.getElementById('root')
);
The App.jsx in the src folder
import * as React from 'react';
import './App.css';
import { MyContainer } from './components/MyContainer/index';
class App extends React.Component {
render() {
return (
<div className={ 'App' }>
<header className={ 'App-header' }>
<h1 className={ 'App-title' }>
</h1>
</header>
<MyContainer />
</div>
);
}
}
export default App;
PS: I have been able to add React to my file... But this particular component that I want to add only works with NPM Start. and as you can see in the index.html file shown above is says
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
which is exactly what I aim to change. if any one can provide some guidance or help about this, would be much appreciated.

If you just want to use React within an HTML file within a browser maybe you could just include the React library with a script tag as well as your custom React scripts with script tags as well. Their documentation has a nice example of just using React within an HTML file. I created a Codebox with their sample example for this below where the like button is using react. However, if you want to use JSX syntax you will have to use Babel, to transpile JSX into native JavaScript, and link the library like such:
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
create_react_app gives you a lot of bells and whistles so you don't have to worry about setting up build configurations using tools such as webpack, babel, eslint, etc.. but this meant to give you a head start on building out an application so you can focus on the application itself and not configuration settings. Behind the scenes it's using webpack-dev-server to serve up your application, but for your use case I think it would be best to just add React as a script tag to an existing HTML page
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Add React in One Minute</title>
</head>
<body>
<h2>Add React in One Minute</h2>
<p>This page demonstrates using React with no build tooling.</p>
<p>React is loaded as a script tag.</p>
<!-- We will put our React component inside this div. -->
<div id="like_button_container"></div>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<!-- Load our React component. -->
<script src="like_button.js"></script>
</body>
</html>
Hopefully that helps!

Related

My react app doesn't render as expected. Why is this happening?

So, I am learning React (from this video) and I am stuck in the beginning.
I set up 2 files: App.js and index.html, just like in the video.
I installed the npm packages react and react-dom too.
This is the following code of the files;
index.html :
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div id="root"></div>
<script src='/App.js'></script>
</body>
</html>
App.js :
import React from 'react'
import ReactDOM from 'react-dom'
export default ReactDOM.render(<h1>Test</h1>, document.getElementById("root"));
Both files are in the same directory.
But whenever I hit the index.html in the browser it returns me nothing, and I am just following the instructions from the video that I mentioned. Why is this happening?
Thanks!
You didn't include the react js file (the framework) in your html file.
From the video, you can see on the left pane the "dependencies" section. It has both react and react-dom as dependencies.
In your App.js you are trying to export the ReactDOM.render() statement.
Try changing it to this
import React from 'react'
import ReactDOM from 'react-dom'
ReactDOM.render(<h1>Test</h1>, document.getElementById("root"));
If your index.html file is just HTML and not a React component, then you can't require it in the same way you would do with a JS file.
However, if you are using Browserify — there is a transform called stringify which will allow you to require non-js files as strings. Once you have added the transform, you will be able to require HTML files and they will export as though they were just strings.
Once you have required the HTML file, you'll have to inject the HTML string into your component, using the dangerouslySetInnerHTML prop
var __html = require('./index.html');
var index= { __html: __html };
React.module.exports = React.createClass({
render: function() {
return(
<div dangerouslySetInnerHTML={index} />
);
}
});
This technique goes against a lot of what React is about though. It would be more natural to create your templates as React components with JSX, rather than as regular HTML files.

how to use react component in angular js

I made two apps one is for angularjs and one is to react. Now the problem is I include the react build in angularjs app and try to initialize the '' component but when I run the code it says Test is not defined.
Can someone help me with this or give me any idea how I can get out of this problem.
React Component:
import React from 'react';
import ReactDOM from 'react-dom';
class Test extends React.Component {
render() {
return (
<div>
Hello
</div>
);
}
}
angular Js Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body ng-app="angular-app">
<div id="root"></div>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.1/angular.min.js"></script>
<script src="react/dist/build.js"></script>
<script>
ReactDOM.render(<Test/>, document.getElementById('root'));
</script>
</body>
</html>
You should write the following code in your react app and then load your bundle file in angularJS app.
ReactDOM.render(<Test/>, document.getElementById('root'));
Thing is, you cannot use jsx inside browser, jsx is usually transpiled using Babel into JavaScript function calls.
So 1. <Test /> will never work inside browser, you need to Babel that.
You need to expose react to you angularjs, best way I can think of is
// In react, instead of exporting component, export a function that mount component in given HTML
Export default (elm) => ReactDOM.render(<Test/>, elm)

How to import a script for my project ? ReactJS

I'm a project and that project have a "bootstrap" own, and i would want to import it for my render.
I created an archive HTML with the scripts:
<html>
<head>
<script> //1.www.s81c.com/common/v18/css/www.css</script>
<script> //1.www.s81c.com/common/stats/ida_stats.js</script>
<script> //1.www.s81c.com/common/v18/js/www.js</script>
</head>
</html>
and imported in my App.js:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
***import './V18.html'***;
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 class="nameOfClassImported" className="App-title">BEM VINDX</h1>
</header>
To get started, edit <code>src/App.js</code> and save to reload.
</div>
);
}
}
export default App;
but given that error:
> Failed to compile.
./src/V18.html
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type.
| <html>
| <head>
| <script> //1.www.s81c.com/common/v18/css/www.css</script>
Resume:
I want to import scripts for i to use in my App.js
I think the tag for the .css file should be <link>.
There are multiple ways to import external scripts. One way that does work is to move these scripts to the <head> of your public/index.html.
/// public/index.html ///
<html>
<head>
<script src="//1.www.s81c.com/common/stats/ida_stats.js"></script>
<link href="//1.www.s81c.com/common/v18/css/www.css" rel="stylesheet">
<script src="//1.www.s81c.com/common/v18/js/www.js"></script>
/// rest of public/index.html ///
Those scripts will be downloaded when your page loads and you can access the variables in those scripts on the window object. After linking to these from your public/index.html, restart your React app, then open the console with F12 or Command-Option-i and type window into the console. There you will see all the global functions that are available from within your React app including window.IBMCore, window.Modernizr, etc
Have you tried this?
<script type='text/javascript' src='..//1.www.s81c.com/common/stats/ida_stats.js'></script>
and for following can you try a regular <link /> instead of <script>
import those in index.html path is public.index.html. Because your app put in one of div of same html page.
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
Read this how webpack work.
https://webpack.js.org/configuration/externals/
else other way is save file and import at App.js
import './App.scss';

require is not defined

Im building a new React app but get the following error -
"require is not defined"
hello-world.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="react/react.js"></script>
<script src="react/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
</head>
<body>
<div id="example"></div>
<script type="text/babel" src="hello-world.js">
</body>
</html>
hello-world.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(
<App />,
document.getElementById('example')
);
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
Hello World!!!
</div>
);
}
}
export default App;
Im running this from my client and don't have any web server running.
I tried to include http://requirejs.org/docs/release/2.2.0/minified/require.js
but it gives a totally different error.
You're trying to use a CommonJS module from within your browser.
This will not work.
How are you using them?
When you write import ... from ... in ES6 Babel will transpile these calls to a module definition called CommonJS and since CommonJS isn't around in the browser you'll get an undefined error from require().
Furthermore, you're also trying to load RequireJS which uses a different module definition pattern called AMD, Asynchronous Module Definition, and will not take care of the require calls for you. You can wrap them in RequireJS specific calls.
If you want to use CommonJS modules in your code base you need to first bundle them with either Browserify or webpack. The two tools will transform your require calls to some glue magic that you can use within the browser.
But in your specific case, if you remove the import calls and just let the browser take care of and attach the classes you've created to the window object your code should work.
Also, note that when you are using submodules from React without another transpiler you will have to reference the top-level modules. I just know that in some cases there are people who will not wish refactor their projects and alter directories to handle webpack/browserify module imports.
So instead of using the CommonJS import React, {useState, useEffect} from 'react' you can instead reference hooks with React.useEffect() , React.useState().
Just another solution for those who don't want to deal with any refactoring.
Here is a basic hello world example on hooks
The code samples on react website doesn't show the full html document. In summary use React.useEffect and React.useState. Get rid of the import statement.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react#17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
function Example() {
const [count, setCount] = React.useState(0);
// Similar to componentDidMount and componentDidUpdate:
React.useEffect(() => { // Update the document title using the browser API
document.title = `You clicked ${count} times`; });
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
ReactDOM.render(
<Example />,
document.getElementById('root')
);
</script>
</body>
</html>

Hello World in Visual Studio 2015 TSX file ( React.js and TypeScript )

I am new to React.js and TypeScript and am trying to get a simple Hello World sample working. I added react-d.ts, react-dom.d.ts to my Typings folder. When I run the site in debug mode I get "require is not defined" on line 1 of the typescript file. How do I define this?
--------- index.html file: --------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>TypeScript Test</title>
<!-- References. -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.2/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h1>Before React Output</h1>
<div id="content"></div>
<script src="Test.js" type="text/javascript"></script>
</body>
</html>
----------- Test.tsx file: -----------------
import React = require('react');
import ReactDOM = require('react-dom');
interface MyProps {
name: string;
}
class HelloWorld extends React.Component<MyProps, {}> {
constructor(props: MyProps) {
super(props);
}
render() {
return (<div> Hello {this.props.name} </div>);
}
}
ReactDOM.render(<HelloWorld name="World" />, document.getElementById('content'));
Here are my TypeScript settings:
I was able to get this code to work by adding the react-globals.d.ts typescript definitions file to my VS project, but I also had to remove the two lines that did the "import React = 'react';". I guess the CommonJS import syntax is not required for external modules when I am not bundling everything into 1 javascript file.
I could also get the project to work if I created a bundle.js of all the javascript files using Gulp and Browserify. Maybe this is the better way since I don't have to use the script tags for React and it still works.
The problem with this method is that I don't know how to set break points in the individual typescript files. I can only set break points for debugging in the giant bundled javascript file. I finally gave up and logged a call with Microsoft to try and figure out how to make all this new technology work together. Good grief Charlie Brown!
Microsoft got back to me and said that TypeScript version 1.8 (in beta) will solve all of these bundling problems. I guess that means that Gulp and Browserify won't be needed in Visual Studio for bundling anymore.

Resources