I'm new to React. I have a local development server (node http-server) and have installed material-ui package.
According to the material-ui docs, to add a component, I simply import it like any other module:
import Button from '#material-ui/core/Button';
However, when I try this, my webserver is returning a 404 and Firefox console outputs this: Loading module from “http://localhost:8080/node_modules/#material-ui/core/Button/” was blocked because of a disallowed MIME type (“text/html”)
The directory is accessible because I can reference the ./node_modules/#material-ui/core/Button/Button.js file and it is returned by http-server. But if I import that file, I get
SyntaxError: import not found: default.
I've tried importing index.js from that directory, but get same error.
How do I import the Button component (as shown in the material-ui example) correctly?
Here is my code (being served by http-server on localhost:8080)
(I am using npx babel to compile the JSX to js before serving)
test.html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Test React</title>
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
</head>
<body>
<div id="app"></div>
<!-- React scripts -->
<script type="module" src="./test.js"></script>
</body>
</html>
test.js:
import { Mod1 } from './module1.js';
export class TestComponent extends React.Component
{
render()
{
return <h1>Hello world!</h1>;
}
}
export const TestC2 = () =>
{
return <h2>This is a h2</h2>;
}
ReactDOM.render(<div><TestComponent /><TestC2 /><Mod1 /></div>, document.getElementById('app'));
module1.js
// module1
import Button from './node_modules/#material-ui/core/Button';
export class Mod1 extends React.Component
{
constructor(props)
{
super(props);
this.state = {};
}
componentWillMount(props)
{
console.log("willMount", props);
}
componentDidMount(pp, ps)
{
console.log("didMount", pp, ps);
}
render()
{
console.log('render', this.props, this.state);
return <Button />;
}
}
Related
I've just started using react and was using the create-react-app from npm until today. I've gotten the react and reactdom code from
https://unpkg.com/react#15/dist/react.js
https://unpkg.com/react-dom#15/dist/react-dom.js
I've saved the files as:
/Test/react/react.js
/Test/react/react-dom.js
This is my index.js:
<!--/Test/index.js-->
<html>
<head>
<title>React Hello World</title>
</head>
<body>
<div id="root"></div>
<script src="react/react.js"></script>
<script src="react/react-dom.js"></script>
<script src="App.js"></script>
</body>
</html>
I have created a module called Greetings, given below:
//Test/Components/Greetings.js
class Greetings extends React.Component {
render() {
return React.createElement(
"h1",
null,
"Greetings, " + this.props.name + "!"
);
}
}
export default Greetings;
And I've created an App.js, given here:
//Test/App.js
import Greetings from "./Components/Greetings";
ReactDOM.render(
React.createElement(Greetings, { name: "Me" }),
document.getElementById("root")
);
I'm getting this error:
Uncaught SyntaxError: Unexpected identifier
Is there an easy way to import a react module?
import and export are Node.js keywords. On the client-side you don't need them. Simply include your javascript files in the html:
<script src="App.js"></script>
<script src="Greetings.js"></script>
I have a React component that I want to inject into the DOM. This is because my JS will be loaded through a script tag by other website owners, not loaded onto a SPA under my control.
What I want to do is append my Root component into the body of the webpage.
If I do something like this, then it replaces all the contents of my body, which is not what I want.
import React from "react";
import ReactDOM from "react-dom";
class Root extends React.Component {
render() {
return <div>heyyyyyyy</div>;
}
}
if (!module.parent) {
ReactDOM.render(<Root />, document.querySelector("body")); // <-- wrong
}
I want something like document.querySelector("body").appendChild(<Root />). Is this possible?
If you opt for a one-liner :
ReactDOM.render(
<Root />,
document.body.appendChild(document.createElement("DIV"))
)
Running Example:
class Root extends React.Component {
render() {
return <div>It works!</div>;
}
}
ReactDOM.render(
<Root />,
document.body.appendChild(document.createElement("DIV"))
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>
<body></body>
Create the root element and append it to the DOM yourself
const rootEl = document.createElement('div')
document.body.appendChild(rootEl)
class Root extends React.Component {
render () {
return <div>heyyyyyyy</div>
}
}
ReactDOM.render(
<Root />,
rootEl
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div>don't replace me</div>
I put my extended and complex answer cause it may help if you need to import one/multiple react components without npm in server side render:
You may go without NPM/Webpack but you gotta use babel:
In my case it is server side rendering, that's why i cannot use npm
First: import all dependencies and put your main module like this to html :
<script type="module" src="/jsx/mainPage.js"></script>
//specify js, not jsx because babel compiles jsx files to js
<script>
new mainPage({
containerID: "${parentID}"
})
</script>
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
//since babel-watched is used, you dont need babel cdn lib anymore
Second: write your jsx in the next way
//my MainPage.jsx
{ ChildPageComponent } from './childPage.js';
window.MainPage = function(props) {
ReactDOM.render(<MainPageComponent constainerID={props.containerID}/>,
document.getElementById(props.containerID));
}
class MainPageComponent extends React.Component {
render() {
return <ChildPageComponent/>
}
... }
my child page.jsx
export class ChildPageComponent extends React.Component {
render(){
return(<div>helloword</div>)
}
}
But the most helpful is Babel watcher. This bash script helps to install and run babel-watcher. You gotta specify your pathes for source and compiled project files
#!/bin/bash
if [ ! -d "node_modules" ]; then
npm init -y
npm install babel-cli#6 babel-preset-react-app#3
fi
SOURCES=~/Documents/yourpath/project/jsx
OUT=~/Documents/yourpath/project/jsx
npx babel --watch $SOURCES --out-dir $OUT --presets react-app/prod
Sure it help you because i was looking for this way for a long
I'm currently trying to get React to work by CDN.
When I run the index.html file manually it works. But when I put my files onto a web server like XAMPP, I get hit with
Uncaught ReferenceError : require is not defined
index.html:
<html>
<head>
<title>TestApp</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script src="./node_modules/moment/moment.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel" src="./react.js"></script>
</body>
</html>
react.js:
const Aest = ({test}) => {
return (
<div>WATss {test}</div>
)
}
class Test extends React.Component{
constructor(){
super()
this.state={
test: 0
}
}
inc(){
this.setState({
test: ++this.state.test
})
}
render(){
return(
<React.Fragment>
<div>test: {this.state.test}</div>
<button onClick={()=>this.inc()}>Add</button>
<Aest test={this.state.test}/>
</React.Fragment>
)
}
}
ReactDOM.render(<Test />,document.getElementById('app'));
require is not understood by default in some web severs, to allow it to be recognized first. use require js. npm install it. and import it.
I am struggling to find an example of how to set the public path of an output file of a webpack bundle.
The documentation says:
If you don't know the publicPath while compiling, you can omit it and
set __webpack_public_path__ on your entry point.
Like so:
__webpack_public_path__ = myRuntimePublicPath
Would anyone be kind enough to create a JSFiddle example how this can be done?
Nothing has changed after almost two years. It's still surprisingly difficult to find an example of setting public path for webpack at runtime.
Prerequisites
webpack 4.5.0
an app big enough to leverage code splitting
For simplicity let's say our html lives in index.html and app entry point is app.js
An example that works
index.html
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<div id="app"></div>
<script type="application/javascript">
window.resourceBasePath = '/path/to/scripts/on/server/';
</script>
<script type="application/javascript" src="/path/to/scripts/on/server/app.js"></script>
</body>
</html>
app.js
// it is important to set global var before any imports
__webpack_public_path__ = window.resourceBasePath;
import React from 'react';
import ReactDOM from 'react-dom';
import {store, history} from './store';
const render = () => {
import('./root').then((module) => {
const Root = module.default;
ReactDOM.render(
<Root
store={store}
history={history}
/>,
document.getElementById('app'),
);
});
};
render();
if (module.hot) {
module.hot.accept('./root', render);
}
An example that doesn't work
Webpack publicPath documentation says it's enough just to set a global variable with the right name. I did that:
index.html
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<div id="app"></div>
<script type="application/javascript">
__webpack_public_path__ = '/path/to/scripts/on/server/';
</script>
<script type="application/javascript" src="/path/to/scripts/on/server/app.js"></script>
</body>
</html>
app.js
import React from 'react';
import ReactDOM from 'react-dom';
import {store, history} from './store';
const render = () => {
import('./root').then((module) => {
const Root = module.default;
ReactDOM.render(
<Root
store={store}
history={history}
/>,
document.getElementById('app'),
);
});
};
render();
if (module.hot) {
module.hot.accept('./root', render);
}
In this case my app fails complaining in console it couldn't load 0.js from current path to index.html. Which means that setting public path didn't have any impact.
import React from 'react';
class App extends React.Component {
constructor(){
super();
this.update = this.update.bind(this)
this.state = {val: 0}
}
update(){
this.setState({val: this.state.val + 1});
}
componentWillMount() {
console.log("Will mount");
}
render() {
return (
<button onClick={this.update}>
{this.props.txt} - {this.state.val}
</button>
);
}
componentDidMount() {
console.log("mounted");
}
}
App.defaultProps = {txt: 'button'}
I'm trying to follow a tutorial about React, to create a simple button that has a "txt" value that increases by one every time it's clicked. A separate main.js loads this file like this:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('app'));
The error says that the element I'm targeting isn't a string, but 'app' is a string, so I'm not sure why it's not rendering. Any ideas? Here's the index.html file I'm loading:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lesson 11</title>
</head>
<body>
<div id="app"></div>
<script src="index.js"></script>
</body>
</html>
Thanks for any help!
You need export App class component from ./App file
export default class App extends React.Component {
ES6 Modules