React import background image - javascript

Trying to import a jpeg image to use as my background in React, but keep getting error msg
Error: Can't resolve '/img/dots.jpeg' in 'D:\Developer\mysite\src'
My App.css
.App {
text-align: center;
background-image: url('/img/dots.jpeg');
}
My App.js
import './App.css';
function App() {
return (
<div className="App" >
<h1>asdasdasd</h1>
</div>
);
}
export default App;
My project structure:
My understanding is as long as the image is in the src folder I can access it relatively through URL(). Can someone tell me what I am doing wrong?

/img/dots.jpeg is indicating that it's in the root of your project, whereas ./img/dots.jpeg will indicate that the img directory is in the same directory as the App.css file.

You can use module-resolver plugin and update your babel config with
{
"plugins": [
["module-resolver", {
"root": ["./src"],
"alias": {
"test": "./test",
"underscore": "lodash"
}
}]
]
}
#same configuration available in the link. Then you can refer your image with complete path

it seems there is wrong in importing the file in your css,
you are not telling the exact position to look for the file
.App {
text-align: center;
background-image: url('/img/dots.jpeg');
}
add these above lines it will solve the problem

Related

Vue js component problem because of giving the following error in an image [duplicate]

I am new In Vue.js Technology. I am getting an error while running my Vue application. Don't know where I am wrong, please try to fix my error.
This is the Temp File where I am getting an Error.
Temp.vue
<template>
<div>
<h1>Hello Ashish</h1>
<h2>{{name}}</h2>
</div>
</template>
<script>
export default {
name: "Temp",
};
</script>
App.vue
<template>
<img alt="Vue logo" src="./assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
<!-- <HomeComp msg="Hello Harshal"/> -->
<!-- <ForLoop/> -->
<Temp/>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
// import HomeComp from './components/HomeComp.vue';
// import ForLoop from './components/ForLoop.vue';
import Temp from './components/Temp.vue';
export default {
name: 'App',
components: {
HelloWorld,
// HomeComp,
// ForLoop
// Demo,
Temp
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Add this to the "rules"-section at eslintrc.js if you don't want to change component names:
'vue/multi-word-component-names': 'off',
(Taken from the response of #lifecoder above, but can't add it as a comment due to my reputation)
Your linter just tells you, that your component name should be a multi word like MyTemp instead of just Temp.
You could rename the component or disable the linting rule.
Add "rules": {"vue/multi-word-component-names": "off"} to eslintConfig in package.json
There are several things you can do to help:
To name two floods
That you can add this code to your project:
{
"vue/multi-word-component-names": ["error", {
"ignores": []
}]
}
Be sure to look at the full document on this site.
So I also encounter the same error, All you have to do is change the name of the component from Temp to MyTemp or any other two word combination.
Here, you can also see and take the idea from the vue/multi-word-component-names Documentation, They explained things very clearly and is very helpful :-
https://eslint.vuejs.org/rules/multi-word-component-names.html
Just use a multiple word name, like "MyCounters", not only "Counter".
export default {
name: "MeusContadores",
components: {
"app-contador": MeuContador,
},
};
I recommend to change the name of the Component. Temp to MyTemp.
So replace every where you have Temp to MyTemp
And try by renaming the declaring part like this instead of MyTemp
<my-temp />
Go to vue.config.js file
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
// Add this line of code to disable lintOnSave
lintOnSave: false
})
In your component
Export default {
Name : '( this name )'
This name should be multi-word
For example
(mytepm)📛
(MyTemp)🟢
In <script setup> syntax the component name is inferred from the file name which should be written in PascalCase format like
TempComp.vue
or in kebab-case format :
temp-comp.vue
other format like tempComp or temp-Comp are accepted but they look bad
for more details please check rule-details

Global Variables : Stylus Vue Vite

I would like to create and use stylus variables globally in my Vue Vite project. How can I import stylus variables globally to use within the script section of my SFC?
Here's my Vite config:
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'#': path.resolve(__dirname, './src'),
},
},
css: {
preprocessorOptions: {
styl: {
additionalData: `#import "#/styles/styles.styl"`
}
}
}
})
In my styles.styl file I define a variable like:
contentSideMargin = 50px
In my SFC I try to use a style from styles.styl such as
<style lang="stylus" scoped>
#main-container
padding: $contentSideMargin /* have also tried `contentSideMargin` */
</style>
but it does not work.
—
EDIT: adding package.json. There are no visible errors, the variable is passed directly into the css rather than its value.
{
"name": "project",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"pinia": "^2.0.17",
"pug": "^3.0.2",
"vue": "^3.2.37",
"vue-router": "^4.1.3"
},
"devDependencies": {
"#vitejs/plugin-vue": "^3.0.0",
"stylus": "^0.58.1",
"stylus-loader": "^7.0.0",
"vite": "^3.0.0"
}
}
METHOD A) - CONFIGURING VITE FOR STYLUS USING additionalData PROPERTY
This is the solution You have been searching for
vite.config.js:
import { defineConfig } from 'vite'
import path from 'path'
import vue from '#vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
css: {
preprocessorOptions: {
stylus: {
additionalData: `#import "${path.resolve(__dirname, 'src/assets/global_variables.styl')}"`
}
}
},
})
METHOD B) - IMPORTING STYLUS VARIABLES IN CSS
If you don't want to custom-configure how Vite should bundle your code, all your <style lang="stylus" scoped> must contain definitions of stylus variables that you are going to use in the component.
Either u can define the variables explicitly at the beginning of <style lang="stylus" scoped> or if you have variables definitions in a separate file, you can import that file:
App.vue:
<template>
<div id="my-div">THIS IS MY DIV</div>
</template>
<style lang="stylus" scoped>
#import "./assets/global.styl";
#my-div {
padding: 1rem;
color: $c-text;
background-color: $c-bg;
}
</style>
assets/global.styl:
$c-bg = red
$c-text = yellow
METHOD C) - CONFIGURING VITE WITH CUSTOM PLUGIN FOR STYLUS:
If you prefer not to use import within your components' <style> tags, you can configure Vite to automatically inject stylus files into the CSS of your app by including a custom Vite plugin vite-stylus-import-plugin.js. An advantage of this method over method A is that you can extra-customize the transformation of your stylus files.
vite-stylus-import-plugin.js:
import path from 'path'
export function importStylus() {
return {
name: 'vite-stylus-import-plugin',
async transform(code, id) {
if (/.stylus$/g.test(id)) {
return {
code: `
#import "${path.resolve(__dirname, 'src/assets/global_variables.styl')}"
${code}
`,
map: null,
}
}
return null
}
}
}
After that you can use that plugin in your Vite config file:
vite.config.js:
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import { importStylus } from './vite-stylus-import-plugin.js'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), {
...importStylus(),
enforce: 'pre',
}]
})
WORKING DEMOS
I have a working demo for the last two methods HERE - GitHub repo HERE. In the demo, the big red <div> element was styled using the method B, the blue <div> was styled using the method C. The method A is not in my demo, but it works too
I think that instead
contentSideMargin = 50px
...
<style lang="stylus" scoped>
#main-container
padding: $contentSideMargin /* have also tried `contentSideMargin` */
</style>
The code should be
$contentSideMargin = 50px
...
<style lang="stylus" scoped>
#main-container {
padding: $contentSideMargin;
}
</style>
Thanks to #DVN-Anakin comment and the link provided in the comment ( github.com/TOA-Anakin/Vite-Vue3-TS-template) to a working boilerplate - it's easy to spot the differences
In short: dear stackoverflow users - please read the comments! Members here put their best effort to try to assist without making to much noise (hence comments). If you skip them or not reading them properly - you may loose some vital information that will help you to solve your problem (which is kinda of what we are doing here in the first place)

CSS module is not working in react 16.13.1

I want to style components in react JS. I tried several ways to do that. When I try to create a CSS object and apply it to the component in the same JS file, then it is working. But when I try to apply CSS from external CSS file and import it in the JS file then it is not working. And I have also tried to save that file as filename.module.css. But it didn't help me.
The list of installed node modules and their versions is given below.
> #material-ui/core#4.9.11
> #material-ui/icons#4.9.1
> firebase#7.14.1
> react#16.13.1
> react-dom#16.13.1
> react-router-dom#5.1.2
> react-scripts#3.4.1
In webpack.config.js file of react-script module, I found below code:
const cssRegex = /\.css$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
So I guess my react project is supporting CSS files as well as SCSS and SASS files. Did I understand correctly?
header.module.css file:
.heading {
color: '#3592EF';
font-weight: '600';
letter-spacing: '2px';
}
.navButton {
color: '#444';
font-size: '16px';
padding: '4px 8px';
margin: 'auto';
margin-right: '15px';
}
Header.js file:
import React from 'react';
import { Button } from '#material-ui/core';
import styles from './header.module.css';
export default class Header extends React.Component {
render() {
return (
<div>
<span className={styles.headling}>Heading element</span>
<Button className={styles.navButton}>Home</Button>
<Button className={styles.navButton}>About</Button>
</div>
);
}
}
The output is coming with the Heading element and Home, About button. But without CSS style.
How can I solve this issue?
Thank you.
CSS module is included in react
all you have to do is building a file with the correct name like "example.module.css" and import it with the correct path if it's in the same folder `import tst from 'example.module.css' or whatever path it is in, you can replace "tst" with any any name you like.
and then you can use it in className like
<button className={tst.buttonPrimary}>Submit /button>
this video can help you more:
https://www.youtube.com/watch?v=Udf951dyTdU
Generally custom components do not accept className prop if it is not propagated to the inner of the component.
Looking in the material ui react components Button documentation, this component cannot have className property.
https://material-ui.com/components/buttons/
It means, you cannot use it. To convince your self, try to use general html <button> and it will work, you see.
Edit: grammar
first : open your terminal and run "npm install css-loader style-loader --save-dev"
These loaders enable Webpack to bundle CSS files
Second: in your webpack.config.js file, add the new loaders for interpreting CSS files:
module.exports = {
...
module: {
rules: [
...
*///
{
test: /\.css$/i,
exclude: /node_modules/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
modules: true,
},
},
],
},
*////
],
},
...
};

Distributing React UI Library with styled components

I am a junior developer who just started working in a company.
I have a bit of experience in React and could not solve the current situation.
The situation i am having a trouble with is that when I import from the library that I have distributed in npm, my React project cannot recognize the styled components.
I get this error on my project.
enter image description here
I have researched and realized that the babel needs more options such as using
"babel-plugin-styled-components" option.
Unfortunately, this did not work after using the command and distributed with the commands
yarn build == webpack --mode production
Is there anyway that I can use styled-components library??
thank you!
P:S: I think I need to put more information.
Many people thankfully answered my question but I tried them and I got an another error.
enter image description here
P.S:
My file structure:
enter image description here
My code of Button
export const StyledButton = styled.button`
background-color: white;
border-radius: 3px;
border: 2px solid palevioletred;
color: palevioletred;
margin: 0.5em 1em;
padding: 0.25em 1em;
${props => props.primary && css`
background: palevioletred;
color: white;
`}
`;
export default class Button extends React.Component {
constructor(props) {
super(props);
console.log("Props:", props);
}
render() {
return (
<div>
<StyledButton>{this.props.children}</StyledButton>
{/* <button> {this.props.children} </button> */}
</div>);
}
}
My index.js of Button
import Button from "./Button";
export default Button;
My index.js of src folder
export * from "./components";
My babel.config.js
module.exports = function BabelConfigJS(api) {
api.cache(true);
const presets = ["#babel/preset-env", "#babel/preset-react"];
const plugins = [
"styled-components",
[
"#babel/plugin-transform-runtime",
{
corejs: 2,
helpers: true,
regenerator: true,
useESModules: false,
},
],
[
"#babel/plugin-proposal-class-properties",
{
loose: true,
},
],
];
return {
sourceType: "unambiguous",
presets,
plugins,
};
};
PS: Error code
enter image description here
enter image description here
enter image description here
The error (which really is just an Eslint complaint) does not refer to using styled-components at all!
It's just saying components should be in PascalCase, not camelCase as you have now.
That is, instead of <styledComponent />, it'd be <StyledComponent />.
You just need to change the component name to be Uppercased, it has nothing to do with babel, etc.
// not <styledButton/>
<StyledButton/>
It is a requirement from React as in JSX lower-case tag names are considered to be HTML tags.

Using styled-components results in `cannot read withConfig of undefined`

When attempting to transpile the Spacing.js file, it results in an undefined import even when styled-components was seemingly being imported and used (in the same way) successfully in other files. Even when removing the styled-components babel plugin, a similar error occurs.
.babelrc
{
"presets": [["es2015", { "modules": false }], "react-native"],
"plugins": [
["styled-components", { "displayName": true }],
"react-hot-loader/babel",
"react-native-web",
"transform-decorators-legacy",
"transform-class-properties"
],
"env": {
"production": {
"plugins": [
"transform-react-inline-elements",
"transform-react-constant-elements"
]
}
}
}
Spacing.js - Code before transpilation
import React, { Component, Node } from "React";
import styled from "styled-components";
type Props = {
size: string,
color: string,
fullWidth?: boolean
};
class SpacingComponent extends Component<Props> {
render(): Node {
const { size, color, fullWidth = false } = this.props;
return <Spacing size={size} color={color} fullWidth={fullWidth} />;
}
}
const Spacing = styled.View`
height: ${props => props.size}px;
background-color: ${props => props.color || "transparent"};
width: ${props => {
return props.fullwidth ? "100%" : props.size + "px";
}};
`;
export default SpacingComponent;
Generated code for importing and resolving styled-components
Generated code for using the styled-components library (v3.2.5)
The resulting error
Another example can be seen when removing the styled-components babel plugin from the babelrc, thus the withConfig is not added.
Generated error with no styled-components babel plugin
Generated code making this error
Is babel or webpack adding .default when it doesn't need to, if so, how could I investigate why?
try doing styled(View) instead of styled.View
Not sure if this is going to be helpful to anyone but for me the same error was triggered like this style.something and fixed using an html element eg style.span

Categories