How to serve multiple HTML files with React? - html

I want to build a web application with React with multiple HTML pages.
For example login.html and index.html. I've created these HTML pages and mapped them to URIs with my backend. So I have localhost:8080/login and localhost:8080/index. Unfortunately, React only uses the index.html file to render content!
So index.html works and the React content is shown: localhost:3000/index.html
<!-- index.html -->
...
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="wizard"></div>
</body>
...
<!-- index.tsx -->
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import FetchData from "./FetchData";
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(
<div className="d-flex flex-column">
<div className="bg-dark text-light AppHeading">Self-Service-Webwizard</div>
<div className="bg-white"><FetchData /></div>
</div>,
document.getElementById('wizard') as HTMLElement
);
registerServiceWorker();
But wizardLogin.html doesn't show the React content: localhost:3000/wizardLogin.html
<!-- wizardLogin.html -->
...
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div>Wizard login</div>
<div id="wizardLogin"></div>
</body>
...
<!-- LoginPage.tsx -->
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import './index.css';
import registerServiceWorker from './registerServiceWorker';
import LoginForm from "./LoginForm";
ReactDOM.render(
<div>
<div><h1>Wizard Login.tsx</h1></div>
<div><LoginForm/></div>
</div>,
document.getElementById('wizardLogin') as HTMLElement
)
;
registerServiceWorker();
Am I doing something wrong or is it not possible to serve multiple HTML files with React?
Github: https://github.com/The-Taskmanager/SelfServiceWebwizard

if you are use create react app you must eject your project first
because you must change your entry point in Webpack configuration
first eject ( if you do not have webpack config file )
npm run eject
and after that go to config file
in webpack.config.js
entry: {
index: [
require.resolve('react-dev-utils/webpackHotDevClient'),
require.resolve('./polyfills'),
require.resolve('react-error-overlay'),
paths.appIndexJs,
],
admin:[
require.resolve('react-dev-utils/webpackHotDevClient'),
require.resolve('./polyfills'),
require.resolve('react-error-overlay'),
paths.appSrc + "/admin.js",
]
},
output: {
path: paths.appBuild,
pathinfo: true,
filename: 'static/js/[name].bundle.js',
chunkFilename: 'static/js/[name].chunk.js',
publicPath: publicPath,
devtoolModuleFilenameTemplate: info =>
path.resolve(info.absoluteResourcePath),
},
after that you should add Wepack plugin and added that to your project
new HtmlWebpackPlugin({
inject: true,
chunks: ["index"],
template: paths.appHtml,
}),
new HtmlWebpackPlugin({
inject: true,
chunks: ["admin"],
template: paths.appHtml,
filename: 'admin.html',
}),
also you should rewrite urls
historyApiFallback: {
disableDotRule: true,
// 指明哪些路径映射到哪个html
rewrites: [
{ from: /^\/admin.html/, to: '/build/admin.html' },
]
}
you can read this page for more informations
http://imshuai.com/create-react-app-multiple-entry-points/

Ejecting the app didn't seem like the right option. I found this answer which seems to work better.
Here is a quote from the answer.
How to model a react application as a multi page app. There are many
ways, however, one would be to structure your files like so:
./app --> main page for your app
./app/page1/ --> page 1 of your app
./app/page2/ --> page 2 of your app
...
In this way, each 'page' would contain a self contained react project.
Your main application page could contain hyperlinks that load these
pages, or you could load them asynchronously in your javascript code.
An alternative which I am using right now is to use a different toolchain. I am using Gatsby which has support for multiple pages. You could also use next.js, however it requires a nodejs express server as the backend.

I think you need a router. Here is great react router library which you can use
https://reacttraining.com/react-router/web/example/basic

So far I've learned that React native doesn't support multiple HTML pages because it's an single page application. I kept index.html as single HTML page and solved the issue with conditional rendering in react. When a condition is fullfilled then I'm rendering another React .tsx-file.

Related

React Drag Drop Html File Parse Into Json

I am making this post, as so far with my React program, I have used React Drop-Zone to create a drag drop place, but what I am trying to do is when a local html file is button submitted, I want it to go to a specific / then grab the data from the new local / url.
I'm wondering whether this is possible with just React, or will I need to use Express to create a server, so on submit it uploads it to finish the task?
Upload Local Html File > go to specific / > once inside grab data from page.
Is this possible? or is a API needed?
import React from 'react';
import { useDropzone } from 'react-dropzone';
function DropZoneComponent({ open }) {
const { getRootProps, getInputProps, acceptedFiles } =
useDropzone({});
const files = acceptedFiles.map((file) => (
<li key={file.path}>
{file.path} - {file.size} bytes
</li>
));
return (
<div className="container">
<div {...getRootProps({ className: "dropzone" })}>
<input {...getInputProps()} />
<p>Drag The Html File Here</p>
</div>
<aside>
<ul>{files}</ul>
</aside>
</div>
);
}
export default DropZoneComponent;

Problems with using InputMask PrimeVue in Vue3

Im trying to use InputMask from PrimeVue in project on Vue3
I have block in template tag:
<div class="sdf">
<label for="basic">Basic</label>
<InputMask mask="99-999999" v-model="val1" placeholder="99-999999" />
</div>
and i have script:
export default {
data: () => ({
val1: null,
})
}
Everything seems okay, and console doesn't show any errors, but still, input is not visible, only label is shown. What do i do wrong?
It sounds like you didn't register InputMask.
You could register it globally with app.component('InputMask', InputMask):
// main.js
const { createApp } = require('vue')
import PrimeVue from 'primevue/config'
import InputMask from 'primevue/inputmask'
import App from './App.vue'
createApp(App)
.use(PrimeVue)
.component('InputMask', InputMask)
.mount('#app')
demo

why the html content not shown out when running

Now i use visual studio code to do my project. I can build my code without error, but when running, it no show out the content for html file, only have show css like header abd footer. i have click button on header but cannot go to other page.Here is the sample code
code in index.html
<nav>
List
New student
Student feedback
</nav>
Vue router
const router = new VueRouter({
routes: [
{ path: '/home', component: load('home') },
{ path: '/insert', component: load('insert') },
{ path: '/update/:id', component: load('update') },
{ path: '/feedback', component: load('feedback') },
{ path: '*', redirect: '/home' }
]
});
File name and type: _home.html, _insert.html, _update.html, _feedback.html
Can help me see the problem, thank you
I don't think you should edit directly to index.html as Vue is Single Page Application (SPA) framework. Instead, you should use Vue Component for each page.
This video might help you to figure out how to use Vue and Vue Router properly: https://youtu.be/nnVVOe7qdeQ
Edit:
For sake of clarity, Let me build simplified diagram of Vue project for you.
First of all, make sure you create the project via vue cli. It guides you to build your new vue project better.
Let's say we have 3 pages:
Home
About
Another
Each page has its own CSS, HTML (we call it template), and JavaScript in one file, the .vue file. To connect them, we need a first entrance, main.js. Inside of it, we can configure the router.
Inside main.js
import Vue from "vue";
import VueRouter from "vue-router";
import App from "./App.vue";
import HomePage from "./HomePage.vue";
import AboutPage from "./AboutPage.vue";
import AnotherPage from "./AnotherPage.vue";
// This is your router configuration
Vue.use(VueRouter);
const router = new VueRouter({
[
{ path: "/", component: HomePage },
{ path: "/about", component: AboutPage },
{ path: "/another", component: AnotherPage },
],
mode: "history",
});
// Initialize Vue App
new Vue({
router,
render: h => h(App),
}).$mount("#app");
Then, we need to create App.vue and put <router-view /> inside of it.
Inside App.vue source file
<template>
<div id="app">
<router-view />
</div>
</template>
<script>
export default {
// Keep this empty. Except if you
// need to add sidebar or any else.
}
</script>
Now you're ready to create those three pages
Every pages looks like this:
<style scoped>
// Your CSS here
</style>
<template>
<div>
<!-- Your HTML here -->
</div>
</template>
<script>
export default {
data() {
return {
// Your reactive data here
}
},
mounted() {
// Your script here
},
methods: {
// Your functions here
},
}
</script>
That's all I can explain, hope it helps. If I missed something, please don't hesitate to tell me. Thank you!

Render local html file in React Native

I run React Native using Expo for android and I'm trying to render html file (it shows a map image) in local directory, but it doesn't work properly.
I followed several references, installed webview dependencies in expo and npm both.
The problem is that the result is just html code view, not a map image
Please see my result below:
And my react native code is this (very simple) :
import React, { Component } from 'react';
import { WebView } from 'react-native-webview';
const testHtml = require('./arcgis/arc1.html');
export default function App() {
return (
<WebView source={testHtml} startInLoadingState
scalesPageToFit
javaScriptEnabled
style={{ flex: 1 }}/>
);
}
When I compile the html file in online html website, it appears like this:
left - html code, right - result
This html file is just sample file from official gis website so my react native code must be wrong I guess.
How can I fix the problem ?
Thanks.
You have to use this module for rendering html.
https://github.com/archriss/react-native-render-html
Edit: Instead of using HTML file store your HTML into a .js file and export like this
export const MyHTML =
`<p>Here is an <em>ul</em> tag</p>
<ul>
<li>Easy</li>
<li>Peasy</li>
<li><div style="background-color:red;width:50px;height:50px;"></div></li>
<li>Lemon</li>
<li>Squeezy</li>
</ul>
<br />
<p>Here is an <em>ol</em> tag</p>
<ol>
<li>Sneaky</li>
<li>Beaky</li>
<li>Like</li>
</ol>
`;
and then pass MyHTML to yoru HTML renderer.
If you are using react-native CLI, you have to place the local HTML file in specific folders native to ios and android. Meaning you will have two indez.html file: see - https://aboutreact.com/load-local-html-file-url-using-react-native-webview/
For Expo, I used this method:
import { StyleSheet, Text, View } from "react-native";
import { WebView } from "react-native-webview";
import React from "react";
const MyHtmlFile = `
<p>Here is an <em>ul</em> tag</p>
<ul>
<li>Easy</li>
<li>Peasy</li>
<li><div style="background-color:red;width:50px;height:50px;"></div></li>
<li>Lemon</li>
<li>Squeezy</li>
</ul>
<br />
<p>Here is an <em>ol</em> tag</p>
<ol>
<li>Sneaky</li>
<li>Beaky</li>
<li>Like</li>
</ol>
`;
const Screen = () => {
return (
<WebView
originWhitelist={["*"]}
source={{
html: MyHtmlFile,
}}
/>
);
};
export default Screen;
const styles = StyleSheet.create({});
You can use react-native-webview for rendering html file.
Here is an example
import React, { Component } from 'react';
import { WebView } from 'react-native-webview';
const myHtmlFile = require("./my-asset-folder/local-site.html");
class MyWeb extends Component {
render() {
return (
<WebView source={myHtmlFile} />
);
}
}

How to get the HTML output from a rendered component

I am a newbie to the ReactJS world and trying to get into it. I am working on a style guide for which I need to display some HTML code as an example. I am using ReactPrism for that and I am not able to get the HTML output inside my PrismCode component, I have find a work around by using react-to-jsx which shows the JSX code instead of HTML.
This is the code:
import React from 'react';
import {PrismCode} from "react-prism";
import reactToJsx from 'react-to-jsx';
class CodePreview extends React.Component {
render (){
return (
<div>
{this.props.children}
<h5>Code example</h5>
<pre>
<PrismCode className="language-javascript">
{reactToJsx(this.props.children)}
</PrismCode>
</pre>
</div>
);
}
}
export default CodePreview;
So basically I want to render this.props.children (the component) as HTML code and not the content of it in the PrismCode
I even tried the following as shown on https://github.com/tomchentw/react-prism, but it doesn't work. Not sure what I am doing wrong!
<PrismCode className="language-javascript">
{require("raw-loader!./PrismCode")}
</PrismCode>
Have you considered writing your docs in markdown? I added some special tags for react:
```react:mirror
<Slider
value={7}
/>
```
This will show the rendered component and also the JSX syntax highlighted.
```react:demo
<PropsEditor>
<Slider
value={7}
/>
</PropsEditor>
```
This will render the component as well as a live editor to manipulate any props on the component.
```react
<SomeComponent />
```
Will just syntax highlight but not render the component.
At the top of my markdown file I can import any components I am using in the doc:
---
imports:
- import Slider from '../src/slider'
- import PropsEditor from 'props-editor'
---
The advantage of this way is that your docs work as normal markdown and it's easy to get the JSX as you have it as a string.
To get the HTML source I have a "View Source </> button which prints formatted html dynamically when clicked:
The steps are:
on click get the html of the react component
format the html using prism and a beautifier
insert it into the DOM
So wrap your react component and make a reference to the node:
<div ref={(n) => (this.fenceView = n)}>
And on click add the output below the component, relevant bits:
import prismjs from 'prismjs';
import beautify from 'xml-beautifier';
const RE_HTML_COMMENTS = /<!--[\s\S]*?-->/g;
removeCodeSource() {
const existingHtmlCode = this.fenceView.querySelector('.fence-generated-html');
if (existingHtmlCode) existingHtmlCode.remove();
}
renderCodeSource() {
const html = this.fenceView.children[0].innerHTML.replace(RE_HTML_COMMENTS, '');
const fenceCode = beautify(html, ' ');
const highlightedCode = prismjs.highlight(fenceCode, prismjs.languages.html);
this.removeCodeSource();
this.fenceView.insertAdjacentHTML('beforeend',
`<pre class="fence-generated-html language-html"><code>${highlightedCode}</code></pre>`);
}