Javascript reactJs css in javascript in external file - javascript

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.

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])}>

how to write react correctly 17.0.1 on background image css file?

here are the 3 options i tried
.bg {
background-image: url("/images/icons/courier.png")
}
.bg {
background-image: url("./images/icons/courier.png")
}
.bg {
background-image: url("../images/icons/courier.png")
}
icon is located: /public/images/icons/...
see here for more details
gives this error:
./src/components/header/header.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/components/header/header.css)
Error: Can't resolve '/images/icons/courier.png' in 'E:\New project\yamboo\src\components\header'
earlier this code -->
.bg {
background-image: url("/images/icons/courier.png")
}
worked fine in react version 16.13.1
help please, I will be grateful !!! thanks in advance!!!
For time being I have solved the issue by changing the version of "react-scripts" to 3.4.4 in "package.json" file.
More information can be found here -> https://github.com/facebook/create-react-app/issues/9937
const divStyle = {
color: 'blue',
backgroundImage: 'url(' + imgUrl + ')',
};
function HelloWorldComponent() {
return <div style={divStyle}>Hello World!</div>;
}
The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes.
import React from "react";
import hcbgImage from "./hcbg.jpg";
function App() {
return (
<div
class="bg_image"
style={{
backgroundImage: 'url('+hcbgImage+')',
backgroundSize: "cover",
height: "100vh",
color: "#f5f5f5"
}}
>
<h1>This is Text on top</h1>
</div>
);
}
export default App;
In above example, we import the image and store its path in the variable named hcbgImage. If we console log the variable, we get something like /static/media/hcbg.d1e1f550.jpg. It is the path of the image by React.js.

Emotion - pass style object to external library

I am using reactjs-popup, and one of it's props is contentStyle, which allow you to pass css-in-js object to style an internal div in the library.
however when I pass css object with #media in it, the library doesn't deal with it.
I wonder if there is a way to tell emotion to "translate" this object, or somehow wrap the library element, so it can treat the #media query as needed.
this is a code to demonstrate:
/** #jsx jsx */
import { jsx } from '#emotion/core';
import ReactJsPopup from 'reactjs-popup';
import { FC, PropsWithChildren } from 'react';
const Modal: FC<{}> = props => {
const style = {
padding: 0,
minHeight: '100%',
'#media (min-width: 576px)': {
minHeight: 'auto' // <----------- Doesn't work
}
}
return (
<ReactJsPopup contentStyle={style}>
{(close): JSX.Element => (
<div>
BODY
</div>
)}
</ReactJsPopup>
);
};
export default Modal;
Inline style objects currently do not support media queries.
The viable option here is to use the className prop to style the content. As the docs reads:
this class name will be merged with the component element: ex className='foo' means foo-arrow to style arrow, foo-overlay to style overlay and foo-content to style popup content
When using emotion, you can make sure that the selectors are unique using this property.
import { css } from "emotion";
<ReactJsPopup
className={css`
&-content {
color: red;
}
`}
>
</ReactJsPopup>
Note: The & is for the random classname that is going to be added by emotion. Followed by content that is added by the library

creating css rule with "Styled-Components"

I am using the awesome "Styled-Components"
but I am now using another package that wraps an element inside it so I can't push my StyledComponents there as I don't want to change his package.
I saw glamor has a nice trick.
Is that supported with StyledComponents?
import { css } from 'glamor';
let rule = css({
color: 'red',
})
<div {...rule}>
zomg
</div>
If you think about why I need it, here is an example:
this is an external package I'm using:
External = props => (
<div>
<input style={props.inputStyle} className={props.inputClass} />
</div>
);
so you can see I need to pass in a json style or className
so Glamor will work here, but I dont want to use it just for this scenario.
I'm already enjoying StyledComponent
Thanks
If I understood your query, you can define css rules to a component, like this
import styled from 'styled-components'
const Wrapper = styled.div`
color: 'red';
font-weight: bold;
background-color: ${ props => props.color === 'primary' ? 'green' : 'red' }
`
export const Component = () => {
<Wrapper color='primary'>
I have a red text, and bold font-weight.
</Wrapper>
}

Can not get media templates working using styled-components

I am fairly new to styled-components, and I am trying to get media templates working in my react app. It was created using 'create-react-app'
I followed the code posted in styled-components documentation:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import styled from 'styled-components';
const sizes = {
desktop: 992,
tablet: 768,
phone: 376
}
// Iterate through the sizes and create a media template
const media = Object.keys(sizes).reduce((acc, label) => {
acc[label] = (...args) => css`
#media (max-width: ${sizes[label] / 16}em) {
${css(...args)}
}
`
return acc
}, {})
const Content = styled.div`
height: 3em;
width: 3em;
background: papayawhip;
/* Now we have our methods on media and can use them instead of raw
queries */
${media.desktop`background: dodgerblue;`}
${media.tablet`background: mediumseagreen;`}
${media.phone`background: palevioletred;`}
`;
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
header goes here!!!
</div>
<Content/>
</div>
);
}
}
export default App;
Nonetheless, I get the following error:
Line 14: 'css' is not defined no-undef
Line 16: 'css' is not defined no-undef
line 14 is the following: acc[label] = (...args) => css`
What's wrong with that line?
The link to the piece of code where I got this code is here
I'm sorry you're running into troubles. The only thing you need to change is to import the css helper from styled-components!
import styled, { css } from 'styled-components';
That will fix it.
I'd recommend reading our documentation so you're aware of the features the library has. It's not very long but it'll set you up for success. We'll also update the documentation to include the full import! (reference issue)

Categories