how to import custom css to reactjs project - html

I'm really struggling to get a custom bootstrap.min.css into my react project does anyone know how to do this as there isn't much documentation on how to do this or maybe i'm just blind and cant see it
Thanks
Edit: ive tried in my index.html head and it doesnt work
var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');
module.exports = {
context: path.join(__dirname, "src"),
devtool: debug ? "inline-sourcemap" : null,
entry: "./js/client.js",
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: ['react-html-attrs', 'transform-class-properties',
'transform-decorators-legacy'],
}
}
]
},
output: {
path: __dirname + "/src/",
filename: "client.min.js"
},
plugins: debug ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false
}),
],
};
thats my webpack
I am unsure of what the best css loader is if anyone can suggest one that would be great
edit 2
<div className="container" style={backImg}>
<div className="row" style={slidePadding}>
<div className="col-md-12 well well-lg">
<div className="row">
<div className="col-md-12">
<h4>Thinking load from £200 to £3,000? Thinking of repaying from 6 - 24 months? </h4><br />
<Horizontal />
</div>
</div>
<div className="row">
<div className="col-md-12">
<p> </p>
</div>
</div>
<div className="row">
<div className="col-md-12">
<p>Representative Example. Borrow £1,250 - 15 monthly repayments of £166.66. Total cost of credit £1,249.90 which is £1,249.90 interest at 122.96% pa fixed. Total amount repayable £2,499.90. Representative 233.6% APR.</p>
</div>
</div>
</div>
</div>
</div>
this is the main section of the site which you land on
this is basically where i want the css to work on i want to be able to change all the widths and everything so doing it in inline style would be horrible so css file is the only way

You have to do import of the file path in your component(JS) file.For example:
import a from "../styles/bootstap.min.css";

Worked it out myself what i needed to do was in my index.html was add
<link href="./js/styles/bootstrap.min.css" rel="stylesheet">
then install
npm install --save-dev ignore-loader
then in webpack.config.js add
loader: 'babel-loader', 'ignore-loader',
the ignore-loader part and it tells babel not to transpile css files

You just have to import the css file in the root of your app.
see whats the root of your app and just import the file there.
like :
import '../pathToTheFile';
thats it.

Related

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!

How to serve multiple HTML files with React?

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.

How to load static images on ExpressJs

so I have this node/express api that serve MySQL database, has json output like this:
[
{
id: 1,
name: "Laptop Lenovo",
serial: "123-456",
tag: "IT-CL-22052018-001",
image: "/public/images/lenovo.jpg"
},
{
id: 2,
name: "Desktop Dell",
serial: "456-123",
tag: "IT.CD.19052018-002",
image: "public/images/dell.jpg"
},
{
id: 3,
name: "Laptop Dell",
serial: "909090",
tag: "IT.CL.01052018.002",
image: "http://localhost:8000/images/ldell.jpg"
}
]
I tried this express functions each one of it:
app.use(express.static('public'))
app.use('/static', express.static('public'))
var dir = path.join(__dirname, 'public');
app.use(express.static(dir));
And the only way my React app can display the image is by using the full url on the database, like #3.
How I can display the image without using the full url?
Edit: Add Render Function
render() {
return this.state.inventory.map(itemList => {
let item = itemList;
return (
// <div className="tile">
<div className="card margin-all">
<div className="card-content">
<div className="media">
<div>
<figure className="image is-96x96">
<img src={item.image} />
</figure>
</div>
</div>
<div>
<h4>Nama: {item.name} </h4>
<h4>Nomor Seri: {item.serial} </h4>
<h4>ID Tag: {item.tag} </h4>
</div>
</div>
</div>
// </div>
);
})
}
}
Pict
For express middleware app.use(express.static('public')) is fine, problem is you need to use correct path. In you json data, image is public/images/dell.jpg which should be /public/images/dell.jpg but you can use
<img src={ '/' + item.image} />
as well, hope this will help
The route for static assets is /static/ so I assume you must call the images like this (e.g. #2)
app.use('/static', express.static('public'))
But you're requesting it via /public/
{
id: 2,
name: "Desktop Dell",
serial: "456-123",
tag: "IT.CD.19052018-002",
image: "static/images/dell.jpg"
}
So if you want the path from your origin JSON get working change it to
app.use('/public', express.static(__dirname + '/public'));
From express.js documentation:
http://expressjs.com/en/starter/static-files.html
However, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve
So by adding a proxy to React app, I don't need to provide full url to the link.
If the express port is 8000, then put this line in the package.json of the React App, not the Node app.
"proxy": "http://localhost:8000"
Now I can use images/name.jpg and the image will be displayed.

How to use css-modules and bootstrap at same time?

I'm using electron-react-boilerplate for my project and this boilerplate is using css-modules for styling purpose.
I'm having trouble with using bootstrap and custom style at the same place.
Suppose i've a code snippet like,
<div className="container">
<div className="row custom-css">
// other codes...
</div>
in that case 'row' is one bootstrap className and 'custom-css' is my own style className.
please help me to find some solution for these problem so that i can use css-modules and bootstrap together...
You need to import your CSS module styles from a module file specific to this component, then interpolate them into the classname via the returned object...
MyComponent.css
.myCustomClassName {
color: #fff;
}
MyComponent.js
import styles from './MyComponent.css';
<div className={`row ${styles.myCustomClassName}`} />
When output as HTML this would become something like...
<div class="row MyComponent__myCustomClassName___n1cC4ge}` />
So as long as you are loading the bootstrap CSS somewhere that should pick up on both
thanks guys i find it working by adding {} around that
<div className={`row ${styles.myCustomClassName}`} />
I was kinda stuck with this (as to how to load Bootstrap).
I created this rough edit in my webpack config file.
{
test: /(\.bootstrap\.css$|bootstrap-theme.css|bootstrap.css)/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader',
options: {
minimize: true || {/* CSSNano Options */}
}
},
],
},
{
test: /^((?!\.bootstrap|bootstrap-theme).)*\.css$/,
use: [
{
loader: 'style-loader',
},
{
loader: 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
},
{
loader: require.resolve('postcss-loader'),
options: {
// Necessary for external CSS imports to work
// https://github.com/facebookincubator/create-react-app/issues/2677
ident: 'postcss',
plugins: () => [
require('postcss-flexbugs-fixes'),
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
],
flexbox: 'no-2009',
}),
],
},
}
]
},
The rest are covered perfectly by alechill

AngularJs2 - ng2-map not working/showing up

As I was working on a homepage where I really need a simple map like google maps in my angular2 app. Nothing shows up where there should be a map. Sure I'm just missing something.
Under is my System.config
<!-- Configure SystemJS -->
<script>
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
},
'ng2-map': {
main: 'index.js',
defaultExtension: 'js'
}
},
map: {
'ng2-map': 'node_modules/ng2-map'
}
});
System.import('app/js/main').then(null, console.error.bind(console));
</script>
And then there's the Component trying to use the map directive.
import { NG2_MAP_DIRECTIVES } from "ng2-map";
#Component({
selector: 'contact',
templateUrl: '../../../html/contact.html',
directives: [NG2_MAP_DIRECTIVES]
})
And finally the html part:
<div class="ContentRow-Paralax" id="secondAbout">
<div class="topstripe">
</div>
<div class="stripe">
<h2>Trollolol</h2>
</div>
<div class="ContentRow-Paralax">
<ng2-map id="map" [center]="[40.74, -74.18]" default-style="false"></ng2-map>
There is not much else going on I think, and there's no error logs to tell me where I went wrong. Hope you can help me out! =)
You may need to define default markers or set some css on the map container. My maps wouldn't show until I did this.