Why is my CSS not applying to my React components? - javascript

Say I'm creating a React app and have some CSS for components. I've added the style-loader and css-loader to my webpack config here:
module.exports = {
mode: 'development',
entry: './client/index.js',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['#babel/preset-react']
}
}
}, {
test: /\.css$/,
loader: 'style-loader'
}, {
test: /\.css$/,
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/dist',
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './dist'
},
devtool:"#eval-source-map"
};
I have a simple CSS file just to test on one component:
.list-group-item {
border: 1px solid black;
outline-style: solid;
outline-color: red;
outline-width: medium;
}
In my app I'm applying the classname to a element in my component and importing my CSS
import React, { Component } from 'react'
import { connect } from 'react-redux'
import selectContact from '../actions/action_select_contact'
import { bindActionCreators } from 'redux'
import '../styles.css';
class ContactList extends Component {
renderList() {
return this.props.contacts.map((contact) => {
return (
<li
key={contact.phone}
onClick={() => this.props.selectContact(contact)}
className='list-group-item'>{contact.firstName} {contact.lastName}</li>
);
});
}
render() {
return (
<ul className = 'list-group col-sm-4'>
{this.renderList()}
</ul>
);
}
}
function mapStateToProps(state) {
return {
contacts: state.contacts
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ selectContact: selectContact }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(ContactList)
I'm also importing the CSS file in the same way in the ContactList component itself. The rest of the project is here. I would have expected to see an outline around my comtactsList but there is not. There is no CSS when I inspect the page. Why is this not getting applied?

In a react project created with create-react-app or npx create-react-app, I also had the same issue.
I had imported index.css file in my App Component but my styles were not being applied properly to my React Components.
I even tried directly adding index.css file in my html file in the public folder and using link tag to link to my index.css file (which resides within src folder).
<link rel="stylesheet" href="./../src/index.css">
That also didn't work.
Finally, I read an article about 7 ways to apply CSS into React. One best way was to install node-sass into our project and use index.scss ( import './index.scss') into App Component instead of index.css.
And Hurray!!! My CSS worked fine, All the Media Queries started to work fine.
Below is the code snippet you can try.
import React from "react";
import ReactDom from "react-dom";
import './index.scss';
// --- Data to work with ---
const books = [
{
id: 1,
name: 'The Rudest Book Ever',
author: 'Shwetabh Gangwar',
img: 'https://m.media-amazon.com/images/I/81Rift0ymZL._AC_UY218_.jpg'
},
{
id: 2,
name: 'The Rudest Book Ever',
author: 'Shwetabh Gangwar',
img: 'https://m.media-amazon.com/images/I/81Rift0ymZL._AC_UY218_.jpg'
},
{
id: 3,
name: 'The Rudest Book Ever',
author: 'Shwetabh Gangwar',
img: 'https://m.media-amazon.com/images/I/81Rift0ymZL._AC_UY218_.jpg'
},
{
id: 4,
name: 'The Rudest Book Ever',
author: 'Shwetabh Gangwar',
img: 'https://m.media-amazon.com/images/I/81Rift0ymZL._AC_UY218_.jpg'
},
];
const Book = ({ book }) => {
return (
<div className={"book"}>
<img src={book.img} alt="book image" />
<h3>{book.name}</h3>
<p>{book.author}</p>
</div>
)
};
const Books = () => {
return (
<main className={"books"}>
{
books.map(book => {
return (<Book book={book} key={book.id} />)
})
}
</main>
)
};
// Work a bit fast | one step at a time
const App = () => {
return (
<main>
<h2>Books</h2>
<Books />
</main>
)
}
ReactDom.render(<App />, document.getElementById("root"));
/* --- Mobile First Design --- */
.books{
text-align: center;
};
.book{
border: 1px solid #ccc;
text-align: center;
width: 200px;
padding: 1rem;
background: #001a6e;
color: #fff;
margin:auto;
};
h2{
text-align: center;
}
/* --- Adding Media Queries --- */
#media only screen and (min-width: 900px){
.books,.persons{
display:grid;
grid-template-columns: 1fr 1fr;
}
}
To install node-sass, simple do npm install node-sass --save
Then rename all your .css files with .scss and your project with work properly.
The package.json should have the node-sass dependency added as shown below:
"dependencies": {
"node-sass": "^4.14.1",
"react": "^16.8.3",
"react-dom": "^16.8.3",
"react-scripts": "2.1.5"
},
Hope this will help many developers :)

It would be helpful to see your React component as well.
Given this code, you are passing className as a property into the component rather than assigning a class to it:
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
render() {
return (
<div>
/** This line specifically **/
<ContactList className="contactList" />
<ContactDetail />
<AddContactModal />
</div>
);
}
}
Inside your component, you would need to use className={this.props.className} on a regular HTML tag inside of your component in order to pass the className through.

You can add your specific css file to index.js directly. (like this import './master.css'
)

According to the react documentation here the className can be applied to all DOM regular element such as <div>, <a>, ...
Does your CSS works with the regular tag <div className='contactList'>hello</div> ?

Styling React Using CSS
I had a problem with applying css file to my react component, which solved by adding a .module.css extension to my css file name. I found the answer here in w3schools

Related

GatsbyJS file is null - setting relativePath doesn't work

I'm attempting to pull an image: /src/images/es.png
And to display it on a gatsby page. Here's the page code:
import React from "react"
import {
Header,
Image,
} from 'semantic-ui-react';
import { graphql } from 'gatsby'
import Img from 'gatsby-image'
import Layout from '#/components/layout'
import SEO from '#/components/seo'
export const query = graphql`
query {
file(
relativePath: { eq: "images/es.png" },
sourceInstanceName: {
eq: "images"
}
) {
childImageSharp {
# Specify the image processing specifications right in the query.
# Makes it trivial to update as your page's design changes.
fixed(width: 125, height: 125) {
...GatsbyImageSharpFixed
}
}
}
}
`
export default ({ data }) => (
<Layout>
<SEO title="Earthshaker" />
<div style={{ height: '100%' }}>
<Header
as="h1"
style={{
color: 'white',
}}
>
Earthshaker
</Header>
{ JSON.stringify(data) }
{/* <Img fixed={data.file.childImageSharp.fixed} /> */}
</div>
</Layout>
)
Here's the config code:
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: path.join(__dirname, `src`, `images`),
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
Here's my file structure:
- src
- images
- es.png
- components
- heroes
- earthshaker <---- (this is the page code HERE)
I'm expecting the image to get pulled out but I always get file: null. What am I doing wrong?
Assuming that your query works, I'd change your filesystem paths to:
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images/`,
},
},
In addition, I would check the query to see if it gathers the expected result in the GraphQL playground (localhost:8000/___graphql). The rest of the code looks fine.

Vue js Prefetch components

I recently learnt about lazy loading components and started using it. Now I am trying to prefetch the lazy loaded components as well as vue-router routes. But using the chrome devtools I found that lazy loaded chunks are only loaded when we actually navigate to the lazy loaded route (in case of a vue-router route) or when the v-if evaluates to true and the component is rendered (in case of a lazy loaded component).
I have also tried using the webpackPrefetch: true magic string in the router as well as component import statement but doing that does not seem to make any difference.
Project structure:
Master-Detail layout
router config:
import Vue from "vue";
import Router from "vue-router";
Vue.use(Router);
var routes = [
{
path: "/DetailPage",
component: () => import(/* webpackChunkName: "Detail-chunk" */ "AppModules/views/MyModuleName/DetailPage.vue")
},
{
path: "/MasterPage",
component: () => import("AppModules/views/MyModuleName/MasterPage.vue")
}
]
export const router = new Router({
routes: routes,
stringifyQuery(query) {
// encrypt query string here
}
});
export default router;
Master view:
<template>
<div #click="navigate">
Some text
</div>
</template>
<script>
export default {
name: "MasterPage",
methods: {
navigate() {
this.$router.push({
path: "/DetailPage",
query: {},
});
},
},
};
</script>
Details page:
<template>
<div>
<my-component v-if="showComponent" />
<div #click="showComponent = true">Show Component</div>
</div>
</template>
<script>
const MyComponent = () => import(/* webpackChunkName: "MyComponent-chunk" */ "AppCore/components/AppElements/Helpers/MyComponent");
export default {
name: "DetailPage",
components: {
MyComponent,
},
data() {
return {
showComponent: false
}
}
};
</script>
vue.js.config file:
const path = require("path");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
.BundleAnalyzerPlugin;
module.exports = {
publicPath: "some-url",
outputDir: "./some/path",
chainWebpack: webapckConfig => {
webapckConfig.plugin("html").tap(() => {
return [
{
inject: true,
filename: "index.html",
template: "./public/index.html"
}
];
});
},
productionSourceMap: true,
configureWebpack: {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: "server",
generateStatsFile: false,
statsOptions: {
excludeModules: "node_modules"
}
})
],
output: {
filename: "some file name",
libraryTarget: "window"
},
module: {
rules: [
{
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "url-loader",
options: {
limit: 50000,
fallback: "file-loader",
outputPath: "/assets/fonts",
name: "[name].[ext]?hash=[hash]"
}
}
]
}
]
},
resolve: {
alias: {
vue$: process.env.NODE_ENV == 'production' ? 'vue/dist/vue.min.js' : 'vue/dist/vue.js',
AppCore: path.resolve(__dirname, "..", "..", "AppCoreLite"),
AppModules: path.resolve(__dirname, "..", "..", "AppModulesLite")
}
}
}
};
Both the async route and component do get split into separate chunks but these chunks are not prefetched.
When I navigate to the master view, I dont see Detail-chunk.[hash].js in the network tab. It gets requested only when the navigate method in the master page is executed (this the correct lazy load behaviour without prefetch).
Now when I am on the details page, MyComponent-chunk.[hash].js is only requested when the showComponent becomes true (on click of a button)
I've also read at a few places that vue-cli v3 does has prefetch functionality enabled by default and webpack magic string is not needed. I also tried that by removing the webpackPrefetch comment but it made no difference.
I did vue-cli-service inspect and found that prefetch plugin is indeed present in the webpack config:
/* config.plugin('preload') */
new PreloadPlugin(
{
rel: 'preload',
include: 'initial',
fileBlacklist: [
/\.map$/,
/hot-update\.js$/
]
}
),
/* config.plugin('prefetch') */
new PreloadPlugin(
{
rel: 'prefetch',
include: 'asyncChunks'
}
),
UPDATE: I tried removing the prefetch webpack plugin using config.plugins.delete('prefetch'); and then using the webpack magic comment: /* webpackPrefetch: true */ but it made no difference.
How do I implement prefetch functionality?
I solved this by creating a simple prefetch component that loads after a custom amount of time.
Prefetch.vue
<script>
import LazyComp1 from "./LazyComp1.vue";
import LazyComp2 from "./LazyComp2.vue";
export default {
components:{
LazyComp1,
LazyComp2,
}
}
</script>
App.vue
<template>
<Prefech v-if="loadPrefetch"></Prefech>
</template>
<script>
export default {
components: {
Prefech: () => import("./Prefetch");
},
data() {
return {
loadPrefetch: false
}
},
mounted() {
setTimeout(() => {
this.loadPrefetch = true;
}, 1000);
}
}
</script>
Lazy loaded components are meant to be loaded only when user clicks the route. If you want to load component before it, just don't use lazy loading.
vue-router will load components to memory and swap the content of the tag dynamically even if you will use normally loaded component.
You need to implement vue-router-prefetch package for your need. Here is a working demo.
Note: From the working demo, you can notice from console.log that only page 2 is prefetched by the QuickLink component imported from vue-router-prefetch
Code :
import Vue from "vue";
import Router from "vue-router";
import RoutePrefetch from "vue-router-prefetch";
Vue.use(Router);
Vue.use(RoutePrefetch, {
componentName: "QuickLink"
});
const SiteNav = {
template: `<div>
<ul>
<li>
<router-link to="/page/1">page 1</router-link>
</li>
<li>
<quick-link to="/page/2">page 2</quick-link>
</li>
<li>
<router-link to="/page/3">page 3</router-link>
</li>
</ul>
</div>`
};
const createPage = (id) => async() => {
console.log(`fetching page ${id}`);
return {
template: `<div>
<h1>page {id}</h1>
<SiteNav />
</div>`,
components: {
SiteNav
}
};
};
const routers = new Router({
mode: "history",
routes: [{
path: "/",
component: {
template: `<div>
<h1>hi</h1>
<SiteNav />
</div>`,
components: {
SiteNav
}
}
}]
});
for (let i = 1; i <= 3; i++) {
routers.addRoutes([{
path: `/page/${i + 1}`,
component: createPage(i + 1)
}]);
}
export default routers;
I'm working on a mobile app. and wanted to load some components dynamically while showing the splash screen.
#Thomas's answer is a good solution (a Prefetch component), but it doesn't load the component in the shadow dom, and Doesn't pass Vetur validation (each component must have its template)
Here's my code:
main.vue
<template>
<loader />
</template>
<script>
import Loader from './Loader'
const Prefetch = () => import('./Prefetch')
export default {
name: 'Main',
components: {
Loader,
Prefetch
}
}
</script>
Prevetch.vue
<template>
<div id="prefetch">
<lazy-comp-a />
<lazy-comp-b />
</div>
</template>
<script>
import Vue from 'vue'
import LazyCompA from './LazyCompA'
import LazyCompB from './LazyCompB'
Vue.use(LazyCompA)
Vue.use(LazyCompB)
export default {
components: {
LazyCompA,
LazyCompB
}
}
</script>
<style lang="scss" scoped>
#prefetch {
display: none !important;
}
</style>
The loader component is loaded & rendered, then the Prefetch component can load anything dynamically.
since vue-router-prefetch didn't work for me i ended up doing it manually.
Vue 3 Example - all routes are iterated on page load and async components are loaded
const router = createRouter({
history: createWebHistory(),
routes: [{
path: '/',
component: HomeView
}, {
path: '/about',
component: () => import('./views/AboutView.vue')
}]
});
async function preloadAsyncRoutes() {
// iterate all routes and if the component is async - prefetch it!
for (const route of router.getRoutes()) {
if (!route.components) continue;
// most routes have just a "default" component unless named views are used - iterate all entries just in case
for (const componentOrImporter of Object.values(route.components)) {
if (typeof componentOrImporter === 'function') {
try {
// prefetch the component and wait until it finishes before moving to the next one
await componentOrImporter();
} catch (err) {
// ignore failing requests
}
}
}
}
}
window.addEventListener('load', preloadAsyncRoutes);

How can I import text file on React?

I have the following text files in the same directory with my code:
Text1.txt:
This is text1
Text2.txt
This is text2
I want to make a page where when a user clicks a list, each list connects with a text file and the content of text file will be shown in the console. How do I do it?
App.js
import React, { Component } from 'react';
import './Text1.txt';
import './Text2.txt';
class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>Text Lists</h1>
<div>
<h2 onClick={this.showTitle}><li>Click this to show text1</li></h2>
<h2 onClick={this.showTitle}><li>Click this to show text2</li></h2>
</div>
</div>
);
}
}
export default App;
Assuming you are using webpack in your implementation, you will need to use file-loader to do this.
You can read on how here. It's pretty simple if you have done the same with css or any other style loaders.
module.exports = {
module: {
rules: [
{
test: /\.(txt)$/i,
loader: 'file-loader',
options: {
publicPath: 'assets',
},
},
],
},
};
Once the loader is setup you should be able to import it like you would a module
import textfile from './Text1.txt';

Include pictures in JS bundle

My case is the following :
I create a components library for React. So I have a package (bundled with Rollup) that include some pictures (For now only a GIF picture that is used in a component).
The component that use my picture is like this :
import React from 'react';
import PropTypes from 'prop-types';
import ui_spinner from '../../../assets/ui_progress.gif';
/**
* CircularSpinner
* Add a spinner when the user needs to wait
*/
class CircularSpinner extends React.PureComponent {
static propTypes = {
/** Width of the component */
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/** Height of the component */
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/** Style of the component (overload existing properties) */
style: PropTypes.object,
}
static defaultProps = {
width: 128,
height: 128,
style: {},
}
render() {
const { style, width, height } = this.props;
return (
<img src={ui_spinner} width={width} height={height} style={style} alt="ui_progress" aria-busy="true" />
);
}
}
export default CircularSpinner;
When I built it, it's OK.
Now I create a React application with create-react-app and I want to test my components library. To do this, I use npm link (To avoid to push deploy my npm package). My components are OK in my testing application but the picture (the GIF in my CircularSpinner component) is not displayed.
So my question is the following : How to include some assets in a JS bundle with Rollup ? My working approach is correct ?
My Rollup config is the following :
import { uglify } from 'rollup-plugin-uglify'
import babel from 'rollup-plugin-babel'
import url from 'rollup-plugin-url'
const config = {
input: 'src/index.js',
external: ['react'],
output: {
format: 'umd',
name: 'react-components',
globals: {
react: "React"
}
},
plugins: [
babel({
exclude: "node_modules/**"
}),
uglify(),
url(),
]
}
export default config
I build with rollup -c -o dist/index.js.
And the dist folder has the following content :
dist/
assets
92be5c546b4adf43.gif
index.js
My component that use my picture is like this in my testing application :
<img src="92be5c546b4adf43.gif" width="128" height="128" alt="ui_progress" aria-busy="true">
Thanks for your help !
Damien
I found the solution for this issue. This response may help someone :
I update my rollup config to use rollup-plugin-img. I have already used it but my configuration was not correct :
The correct config is the following :
import { uglify } from 'rollup-plugin-uglify'
import babel from 'rollup-plugin-babel'
import image from 'rollup-plugin-img'
const config = {
input: 'src/index.js',
external: ['react'],
output: {
format: 'umd',
name: 'react-components',
globals: {
react: "React"
}
},
plugins: [
babel({
exclude: "node_modules/**"
}),
image({
limit: 100000,
}),
uglify(),
]
}
export default config
My error was that my GIF is a little big and the default limit size is 8192 bytes.
In this case, I have the following error :
Error: Could not load <path of image> (imported by <path of component that use image>): The "path" argument must be of type string. Received type undefined
When I have updated my config to increase the limit, everything is OK

How to apply styles to the react component via css modules

Ive got a problem with applying styles to my React Components.
I generated template to my project via Yeoman. It created a lot of config files, not only webpack.config.js and because of that I'm a little bit confused. As Readme file of react-generator says it support out of the box some features without installing it:
*Different supported style languages (sass, scss, less, stylus)
*Style transformations via PostCSS
According to this I show part of cfg/default.js
'use strict';
const path = require('path');
const srcPath = path.join(__dirname, '/../src');
const dfltPort = 8000;
function getDefaultModules() {
return {
preLoaders: [{
test: /\.(js|jsx)$/,
include: srcPath,
loader: 'eslint-loader'
}],
loaders: [
{
test: /\.css$/,
loader: 'style-loader!css-loader!postcss-loader'
},
{
test: /\.sass/,
loader: 'style-loader!css-loader!postcss-loader!sass-loader?outputStyle=expanded&indentedSyntax'
},
{
test: /\.scss/,
loader: 'style-loader!css-loader!postcss-loader!sass-loader?outputStyle=expanded'
},
{
test: /\.less/,
loader: 'style-loader!css-loader!postcss-loader!less-loader'
},
{
test: /\.styl/,
loader: 'style-loader!css-loader!postcss-loader!stylus-loader'
},
I think this part is responsible for converting .scss files.
So in my todosStyle.scss file I've got this code:
.todos {
display: flex;
flex-flow: row wrap;
justify-content: center;
width: 100%;}
.input {
display: block;
text-align: center;}
.button {
width: 60px;
margin: 5px; }
.label {
display: block;
border: solid 1px; }
Base on this styling I want to style my component Todos.jsx:
import React from "react";
import Todo from "./Layout/Todo.jsx";
import TodoStore from "../../stores/TodoStore.jsx";
import * as TodoActions from "../../actions/TodoActions.jsx";
import styles from '../../styles/todosStyle.scss';
export default class Todos extends React.Component {
constructor() {
super();
this.getAllTodos = this.getAllTodos.bind(this);
this.state = {
todos: TodoStore.getAll(),
};
}
getAllTodos(){
this.setState({
todos: TodoStore.getAll(),
});
}
componentWillMount(){
TodoStore.on('change', this.getAllTodos);
}
componentWillUnmount(){
TodoStore.removeListener('change', this.getAllTodos);
}
createTodo(){
if (this.refs.addTodo.value != ''){
TodoActions.createTodo(this.refs.addTodo.value);
this.refs.addTodo.value = '';
}
}
deleteTodo(todo){
TodoActions.deleteTodo(todo);
}
completeTodo(todo){
TodoActions.completeTodo(todo);
}
render() {
const {todos} = this.state;
const TodoComponents = todos.map(todo =>{
return <Todo key={todo.id} {...todo} completeTodo={this.completeTodo.bind(this, todo)} deleteTodo={this.deleteTodo.bind(this, todo)}/>;
});
return (
<div>
<h1>Todos</h1>
<div class = {styles.input}>
<label class= {styles.label}>Add new Todo</label>
<input ref="addTodo"/>
<button class={styles.button} onClick = {this.createTodo.bind(this)}><i class="fa fa-plus-square-o"></i></button>
</div>
<ul class={styles.todos} class="row">{TodoComponents}</ul>
</div>
);
}
}
but styling isn't applied, although I've imported todosStyle.scss
Could someone help me?
Just a note, its good to add $ on your loader test properties eg. test: /.scss$/, to only match end of file i believe.
i havent seen this before "import styles from '../../styles/todosStyle.scss';"
this kind of says that you are exporting styles from your sass file, perhaps import * as style ... might work, but i haven't used this approach.
try this.
require ('../../styles/todosStyle.scss');
this will bundle your css with the javascript.
then just use the class as you normally would on your render function.
also note; if you would like to create a separate file for your css, you can do that with plugins.
You're using css modules but you haven't turned them on in your Webpack config:
loader: 'style-loader!css-loader!postcss-loader'
becomes
loader: 'style-loader!css-loader?modules!postcss-loader'
As per the css-loader readme https://github.com/webpack/css-loader#css-modules.

Categories

Resources