Distributing React UI Library with styled components - javascript

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.

Related

React components library + SASS modules

I'm starting to work on a react components library and I want to reuse some SCSS code we share with other non-react projects.
To accomplish that, I'm trying to use SASS modules into react component.
The simple use case works fine, but I'm creating a components library and I need to have several style combinations for some components like the button.
Right now, I'm having an issue with the Button component. Component is pretty simple, but it has 3 different variant values.
Here is the Button.tsx file:
import React from "react";
import styles from "./Button.module.scss";
type Variant = "default" | "primary" | "tertiary";
interface Props {
children: String;
variant: Variant;
}
export const Button: React.FC<Props> = ({ children, variant }) => {
return <button className={`${styles.button} ${variant}`}>{children}</button>;
};
and here is the Button.module.scss file:
.button {
border: none;
padding: 0.5rem 1.5rem;
border-radius: 0.25rem;
background-color: grey;
color: white;
&.default {
background-color: green;
}
&.primary {
background-color: red;
}
}
What I expect, is to have a green button if I use the component like <Button variant="default">I'm green</Button>, but instead I'm getting the grey button.
Here is a live example on codesandbox
I'm stuck on this, could somebody help me to apply different styles based on prop values?
<button className={`${styles.button} ${styles[variant]}`}>
Please use classnames npm library.
import cn from 'classnames';
<button className={cn(styles.button, styles[variant])}>

React import background image

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

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,
},
},
],
},
*////
],
},
...
};

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

Javascript reactJs css in javascript in external file

I am using reactjs and trying to get me css inside javascript and finally read the css from an external js file.
Here is the code:
import React from 'react';
import ReactDOM from 'react-dom';
var styles = {
container: {
padding: 20,
border: '5px solid green',
borderRadius: 2
}
};
var myComponent = React.createClass({
render: function() {
return (
<div style={styles.container}>
{this.props.name}
</div>
);
}
});
This works fine but what I need to do is to put the css in an external file.
So I've created a file called general.css.js
And I tried to import it:
import styles from './components/general.css';
I add this import to the top of the page with the other imports.
The problem is that it's not reading the styles.
What I'm I doing wrong here?
Make a new file and put this code in it.
export const style = { container : {
padding: 20,
border: '5px solid green',
borderRadius: 2 }
};
Now in your component file.
import * as styles from './style/location/filename'
Now you can use styles in your render function.
return (
<div style={styles.style.main}>
<h3 style={styles.style.header}>Vote for your favorite hack day idea</h3>
</div>
);
You can directly import your css file in js.
import './style/app.css';
app.css
.page {
background-color:#fafafa;
}
and you can use this class in React component like below.
<div className="page">
Hope it works!!!!
There is a little tool that automates translation from CSS to JSON representation.
Worth checking that out.
Note how the translation adds _ underscores:
div.redcolor { color:red; }
div:hover { color:blue; }
Into:
{"div_redcolor":{"color":"red"},"div_hover":{"color":"blue"}}
Note how the Vishwas Chauhan used starred method of ES6 import export:
In case you use this tool you get one big object, and you can use any method.

Categories