How to use CSS Global Variables? - javascript

first of all thank you so much for your time.
My doubt is simple, but i couldn't find a way to get it working.
So... basically i have a '/pages/_app.js' file:
import '../public/styles/global.css';
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
A global css file '/public/styles/global.css':
:root {
--bg-color: #000;
}
A css module file '/public/styles/header.module.css':
.header {
background-color: var(--bg-color);
}
And finally a home page '/pages/index.js'that uses the css class:
import React from 'react';
import headerStyle from '../public/styles/header.module.css';
export default function Home() {
return <div className={headerStyle.header}>Test</div>;
}
I don't get an error but i didn't manage to refer to the global variables inside the css modules.
Can you guys help me with what am i doing wrong?

If the pages/ directory exists under src/ then the path to the <Home> component should be /src/pages/ and the import for the headerStyle should be the following:
import headerStyle from "../../public/styles/header.module.css";
You just need to go up one more directory.
/*
* #filename /src/pages/index.jsx
*/
import React from "react";
import headerStyle from "../../public/styles/header.module.css";
const Home = () => {
return <div className={headerStyle.header}>Test</div>;
};
export default Home;
Here is a CodeSandbox snippet to demonstrate.

Related

Cannot get SVG as a component to render in CRA

I've written the following TypeScript component:
import React from 'react'
import cx from 'classnames'
/* import SVGs */
import { ReactComponent as Phone } from '../images/phone.svg'
import { ReactComponent as AtDesk } from '../images/at-desk.svg'
import { ReactComponent as Available } from '../images/available.svg'
import { ReactComponent as Blushing } from '../images/blushing.svg'
import { ReactComponent as Skills } from '../images/skills.svg'
import { ReactComponent as Smile } from '../images/smile.svg'
import { ReactComponent as Beach } from '../images/beach.svg'
const selectMiniMe = (name: string): any => {
switch (name) {
case 'available' :
return <Available />
case 'at-desk':
return <AtDesk/>
case 'blushing':
return <Blushing />
case 'skills':
return <Skills />
case 'phone':
return <Phone />
case 'beach':
return <Beach />
case 'smile':
default:
return <Smile />
}
}
/* Import Types */
import Props from './types/props'
/* import Styles */
import styles from './styles.module.scss'
/* Render Component */
export const MiniMe: React.FC<Props> = ({ name, width, position, classes}: Props) => {
return <div className={cx(styles['mini-me'], styles[`w-${width}`], classes)}>
{ selectMiniMe(name) }
</div>
}
export default MiniMe
This component renders without issue as a story in storybook. Everything looks and works exactly as expected and no errors are reported.
When I try to import that component into a brand new Create-React-App TypeScript app. I get the following error:
Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `MiniMe`.
I suspect the issue is loader related but as far as I can tell, I'm doing everything the way that CRA is already configured to work with so I have no idea where it's failing.
For additional reference, here is a link to the repo: https://github.com/foxleigh81/alex-foxleigh-portfolio/tree/2020
I've also managed to find a reference to this exact issue - which as far as I can tell was actually fixed in CRA in 2018, so I've no idea why I'm getting this issue here: https://github.com/facebook/create-react-app/pull/5573
Try to declare the svg module
add this to
// / <reference types="react-scripts" /> declare module '*.svg';
in your react-app-env.d.ts file.
Looking at your repository it seems you are using learna and react setup and are not using create-react-app completely, as I don't see all dependencies that are added to new react app created using create-react-app there in your codebase and hence I am not sure using svg as component will work.
That being said, that will not prevent you from using img tag. I have updated your code and it is working as expected:
import React from 'react'
import cx from 'classnames'
/* Import Types */
import Props from './types/props'
/* import SVGs */
import Phone from './images/phone.svg'
import AtDesk from './images/at-desk.svg'
import Available from './images/available.svg'
import Blushing from './images/blushing.svg'
import Skills from './images/skills.svg'
import Smile from './images/smile.svg'
import Beach from './images/beach.svg'
/* import styles */
import styles from './styles.module.scss'
/* Render component */
export const MiniMe: React.FC<Props> = ({ name, width, position, classes}: Props) => {
const selectMiniMe = (name: string): any => {
switch (name) {
case 'available' :
return <img src={Available} />
case 'at-desk':
return <img src={AtDesk} />
case 'blushing':
return <img src={Blushing} />
case 'skills':
return <img src={Skills} />
case 'phone':
return <img src={Phone} />
case 'beach':
return <img src={Beach} />
case 'smile':
default:
return <img src={Smile} />
}
}
return <div className={cx(styles['mini-me'], styles[`w-${width}`], classes)}>
{selectMiniMe(name)}
</div>
}
export default MiniMe

Having Trouble Accessing Function in Adjacent JS file

Currently in my directory I have App.js and startMenu.js as two separate files.
I would like to access startMenu.js in my App.js file with the correct React formatting.
Currently I can call the function startMenu() using typical javascript syntax, but I for some reason cannot get the React syntax {startMenu} to work. Any ideas would be appreciated.
My code:
import React from "react";
import startMenu from './startMenu';
import credits from "./credits";
var param = 'start';
class App extends React.Component {
renderSwitch(param) {
switch(param) {
case 'credits':
return credits();
default:
/*LINE IN QUESTION */
return startMenu();
}
}
render() {
return (
<div>
{this.renderSwitch(param)}
</div>
);
}
}
export default App;
Thanks!
It is depending how you are exporting your function.
If is doing this:
export default startMenu;
Then you might import that way:
import myFunction from './path';
That way the name does it care. You can call your function with any name when you are exporting by default.
But if you are exporting that way:
export { startMenu };
or
export startMenu;
So than you need import your function by your reall name, and if you are exporting just using export word, all members will be inside an object.
So you need do that:
import MyFunctions from './path';
or doing a import destruction
import { startMenu } from './path';
You'll need to properly export that function:
export function startMenu(...) { ... }
Then import it:
import { startMenu } from './startMenu';
If that's the only thing exported you can always export default and it simplifies the import.
You can only import things that have been exported. Everything else is considered private and is off-limits.
The JSX syntax: {foo} means "Put this data here".
It doesn't mean "Call this variable as a function".
If you want to call it, you need to do so explicitly: {foo()}.

How can I customize the style of a React component shared between lazy-loaded pages?

I'm building a React application and I started using CRA. I configured the routes of the app using React Router. Pages components are lazy-loaded.
There are 2 pages: Home and About.
...
const Home = lazy(() => import('./Home'));
const About = lazy(() => import('./About'));
...
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route path="/about" component={About} />
<Route path="/" component={Home} />
</Switch>
</Suspense>
...
Each page uses the Button component below.
import React from 'react';
import styles from './Button.module.scss';
const Button = ({ children, className = '' }) => (
<button className={`${styles.btn} ${className}`}>{children}</button>
);
export default Button;
The Button.module.scss file just sets the background color of the button to red.
.btn {
background: red;
}
The Button component accepts a className prop which is then added to the rendered button. This is because I want to give freedom to the consumer of the component. For example, in some pages margins could be needed or the background should be yellow instead of red.
To make it simple, I just want to have a different background color for the Button based on the current page, so that:
Home page => Blue button
About page => Yellow button
Each page is defined as below:
import React from 'react';
import Button from './Button';
import styles from './[PageName].module.scss';
const [PageName] = () => (
<div>
<h1>[PageName]</h1>
<Button className={styles.pageBtn}>[ExpectedColor]</Button>
</div>
);
export default [PageName];
where [PageName] is the name of the page and [ExpectedColor] is the corresponding expected color based on the above bullet list (blue or yellow).
The imported SCSS module, exports a class .pageBtn which sets the background property to the desired color.
Note: I could use a prop on the Button component which defines the variant to display (Blue/Yellow) and based on that prop add a class defined in the SCSS file. I don't want to do that since the change could be something that doesn't belong to a variant (e.g. margin-top).
The problem
If I run the application using yarn start, the application works fine. However, if I build the application (yarn build) and then I start serving the application (e.g. using serve -s build), the behavior is different and the application doesn't work as expected.
When the Home page is loaded, the button is correctly shown with a blue background. Inspecting the loaded CSS chunk, it contains:
.Button_btn__2cUFR {
background: red
}
.Home_pageBtn__nnyWK {
background: blue
}
That's fine. Then I click on the navigation link to open the About page. Even in this case, the button is shown correctly with a yellow background. Inspecting the loaded CSS chunk, it contains:
.Button_btn__2cUFR {
background: red
}
.About_pageBtn__3jjV7 {
background: yellow
}
When I go back to the Home page, the button is now displayed with a red background instead of yellow. That's because the About page has loaded the CSS above which defines again the Button_btn__2cUFR class. Since the class is now after the Home_pageBtn__nnyWK class definition, the button is displayed as red.
Note: the Button component is not exported on the common chunk because its size is too small. Having that in a common chunk could solve the problem. However, my question is about small shared components.
Solutions
I have thought to 2 solutions which, however, I don't like too much:
Increase selectors specificity
The classes specified in the [PageName].module.scss could be defined as:
.pageBtn.pageBtn {
background: [color];
}
This will increase the selector specificity and will override the default Button_btn__2cUFR class. However, each page chunk will include the shared components in case the component is quite small (less than 30kb). Also, the consumer of the component has to know that trick.
Eject and configure webpack
Ejecting the app (or using something like react-app-rewired) would allow specifying the minimum size for common chunk using webpack. However, that's not what I would like for all the components.
To summarize, the question is: what is the correct working way of overriding styles of shared components when using lazy-loaded routes?
You can use the following logic with config file for any pages. Also, You can send config data from remote server (req/res API) and handle with redux.
See Demo: CodeSandBox
create components directory and create files like below:
src
|---components
|---Button
| |---Button.jsx
| |---Button.module.css
Button Component:
// Button.jsx
import React from "react";
import styles from "./Button.module.css";
const Button = props => {
const { children, className, ...otherProps } = props;
return (
<button className={styles[`${className}`]} {...otherProps}>
{children}
</button>
);
};
export default Button;
...
// Button.module.css
.Home_btn {
background: red;
}
.About_btn {
background: blue;
}
create utils directory and create AppUtils.js file:
This file handle config files of pages and return new object
class AppUtils {
static setRoutes(config) {
let routes = [...config.routes];
if (config.settings) {
routes = routes.map(route => {
return {
...route,
settings: { ...config.settings, ...route.settings }
};
});
}
return [...routes];
}
static generateRoutesFromConfigs(configs) {
let allRoutes = [];
configs.forEach(config => {
allRoutes = [...allRoutes, ...this.setRoutes(config)];
});
return allRoutes;
}
}
export default AppUtils;
create app-configs directory and create routesConfig.jsx file:
This file lists and organizes routes.
import React from "react";
import AppUtils from "../utils/AppUtils";
import { pagesConfig } from "../pages/pagesConfig";
const routeConfigs = [...pagesConfig];
const routes = [
...AppUtils.generateRoutesFromConfigs(routeConfigs),
{
component: () => <h1>404 page not found</h1>
}
];
export default routes;
Modify index.js and App.js files to:
// index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>,
rootElement
);
...
react-router-config: Static route configuration helpers for React
Router.
// App.js
import React, { Suspense } from "react";
import { Switch, Link } from "react-router-dom";
import { renderRoutes } from "react-router-config";
import routes from "./app-configs/routesConfig";
import "./styles.css";
export default function App() {
return (
<div className="App">
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
<Suspense fallback={<h1>loading....</h1>}>
<Switch>{renderRoutes(routes)}</Switch>
</Suspense>
</div>
);
}
create pages directory and create files and subdirectory like below:
src
|---pages
|---about
| |---AboutPage.jsx
| |---AboutPageConfig.jsx
|
|---home
|---HomePage.jsx
|---HomePageConfig.jsx
|
|---pagesConfig.js
About Page files:
// AboutPage.jsx
import React from "react";
import Button from "../../components/Button/Button";
const AboutPage = props => {
const btnClass = props.route.settings.layout.config.buttonClass;
return (
<>
<h1>about page</h1>
<Button className={btnClass}>about button</Button>
</>
);
};
export default AboutPage;
...
// AboutPageConfig.jsx
import React from "react";
export const AboutPageConfig = {
settings: {
layout: {
config: {
buttonClass: "About_btn"
}
}
},
routes: [
{
path: "/about",
exact: true,
component: React.lazy(() => import("./AboutPage"))
}
]
};
Home Page files:
// HomePage.jsx
import React from "react";
import Button from "../../components/Button/Button";
const HomePage = props => {
const btnClass = props.route.settings.layout.config.buttonClass;
return (
<>
<h1>home page</h1>
<Button className={btnClass}>home button</Button>
</>
);
};
export default HomePage;
...
// HomePageConfig.jsx
import React from "react";
export const HomePageConfig = {
settings: {
layout: {
config: {
buttonClass: "Home_btn"
}
}
},
routes: [
{
path: "/",
exact: true,
component: React.lazy(() => import("./HomePage"))
}
]
};
...
// pagesConfig.js
import { HomePageConfig } from "./home/HomePageConfig";
import { AboutPageConfig } from "./about/AboutPageConfig";
export const pagesConfig = [HomePageConfig, AboutPageConfig];
Edited section:
With HOC Maybe this way: CodeSandBox
create hoc dir and withPage.jsx file:
src
|---hoc
|---withPage.jsx
...
// withPage.jsx
import React, { useEffect, useState } from "react";
export function withPage(Component, path) {
function loadComponentFromPath(path, setStyles) {
import(path).then(component => setStyles(component.default));
}
return function(props) {
const [styles, setStyles] = useState();
useEffect(() => {
loadComponentFromPath(`../pages/${path}`, setStyles);
}, []);
return <Component {...props} styles={styles} />;
};
}
And then pages like below:
src
|---pages
|---about
| |---About.jsx
| |---About.module.css
|
|---home
|---Home.jsx
|---Home.module.css
About.jsx file:
// About.jsx
import React from "react";
import { withPage } from "../../hoc/withPage";
const About = props => {
const {styles} = props;
return (
<button className={styles && styles.AboutBtn}>About</button>
);
};
export default withPage(About, "about/About.module.css");
About.module.css file:
// About.module.css
.AboutBtn {
background: yellow;
}
Home.jsx file:
// Home.jsx
import React from "react";
import { withPage } from "../../hoc/withPage";
const Home = props => {
const { styles } = props;
return <button className={styles && styles.HomeBtn}>Home</button>;
};
export default withPage(Home, "home/Home.module.css");
Home.module.css file:
// Home.module.css
.HomeBtn {
background: red;
}
I would suggest instead of adding both the default styles and the consumer styles, use the consumer's styles over yours and use your as a callback if not supplied. The consumer can still compose your defaults with the composes keyword.
Button.js
import React from 'react';
import styles from './Button.module.scss';
const Button = ({ children, className}) => (
<button className={className ?? styles.btn}>{children}</button>
);
export default Button;
SomePage.module.scss
.pageBtn {
// First some defaults
composes: btn from './Button.module.scss';
// And override some of the defautls here
background: yellow;
}
If you wish, use sass #extends or #mixin instead
EDIT: Haven't tested it, but could it be that just by using composes webpack will make sure to bundle the defaults only once? Thus you're no longer needed to change your Button.js code with the ??
Solution 1
I know this is very obvious, but would work anyway:
Set !important on your overwriting css rules, thus bypassing specificity:
[PageName].module.scss:
.btn {
color: yellow !important;
}
However, most of the strict devs I know would avoid this keyword at all cost.
Why ?
Because when you start to have a lot of !important your css is a nightmare to debug. If you start writing !important rules with higher specificity, you know you have gone too far
It is only meant for corner-cases like yours, you might as well use it.
Solution 2
fix CRA config to enforce style tags order.
It is open-source after all :)
You can give your input on this bug here (upvote might give it more visibility):
https://github.com/facebook/create-react-app/issues/7190
Solution 3 (Update)
You could create a SCSS mixin in a new customButton.scss file, to generate css rules with higher specificity:
// customButton.scss
#mixin customBtn() {
:global {
.customBtn.override {
#content;
}
}
}
We will use two static class names (using the :global selector), because that way their name won't change based on where they are imported from.
Now use that mixin in your pages' SCSS:
// [pageName].module.scss
#import 'customButton.scss';
#include customBtn {
color: yellow;
}
css output should be:
.customBtn.override {
// put everything you want to customize here
color: yellow;
}
In Button.jsx: apply both class names to your button in addition to styles.btn:
// Button.jsx
const Button = ({ children, className = '' }) => (
<button className={`${styles.btn} customBtn override ${className}`}>
{children}
</button>
);
(Note that these are not referenced through the styles object, but the classname directly)
The main drawback is these are not dynamic class names, so you have to watch out to avoid conflicts yourself like we use to do before.
But I think it should do the trick

How to make a stylesheet accessible to only one component react.js

I have multiple stylesheets. Let's say navbar.css and footer.css. I want to use the pseudo-element :root in both of these css files to define variables. However, I don't want the variables to be accessible to the other css file. When I use both of these components, the css files merge together and my styles clash. How can I prevent this?
App.jsx
---
import React from "react";
import Navbar from "./Navbar";
import Footer from "./Footer";
export default class App extends React.Component {
render() {
<Navbar/>
<p>blah blah</p>
<Footer/>
}
}
Navbar.jsx
---
import React from "react";
export default class Navbar extends React.Component {
render() {
<div>...</div>
}
}
Footer.jsx
---
import React from "react";
export default class Footer extends React.Component {
render() {
<div>...</div>
}
}
Navbar.css
---
:root {
bg-col: white;
}
Footer.css
---
:root {
bg-col: black;
}
Now, I have shortened these files to keep it simple, but, the bg-col variables clash with each other. How can I fix this?
You can try with CSS module. In that way, one css file is separate and independent from another. Maybe add a class to that root element and the problem is solved.
Create two files
Navbar.module.css
Footer.module.css
and in your Navbar.jsx and Footer.jsx just import these modules.
Navbar.jsx
---
import React from "react";
import styles from './Navbar.module.css'; // Import css modules stylesheet as styles
import './another-stylesheet.css'; // Import regular stylesheet
export default class Navbar extends React.Component {
render() {
<div className={styles.root}>...</div>
}
}

Using a styled component's rules within `createGlobalStyle`

New to styled components and am wondering if someone might have some advice on how to use a styled component's rules within a call to createGlobalStyle?
The below example is working, but I feel that it is not a great solution as componentStyle.rules is not in the official api docs.
// A styled component
import Modal from '../Modal'
import styled, { createGlobalStyle } from 'styled-components'
const StyledComponent = styled(Modal)`
background-color: pink;
`
createGlobalStyle`
// this div is mounted outside of the React root
.modal-from-external-library {
${StyledComponent.componentStyle.rules}
}
`
Not sure if what I was trying to do was possible, but I ended up solving the problem by exporting the css from the Modal using the css function of styled components.
// Modal.js
const styles = css`
// styles here
`
export default styled.div`
${styles}
`
// ... later
const GlobalStyles = createGlobalStyle`${styles}`
render() { return (<GlobalStyles {...props} />) }

Categories

Resources