Style react-bootstrap button from css - css

I am fairly new to React and JavaScript in general.
I am using Button from react-bootstrap from https://react-bootstrap.github.io/components/buttons/ but I want to style the Button on top of it in my React app from my css file but it does not seem to apply.
my Home.js file looks like
import React from "react";
import '../App.css'; // Reflects the directory structure
export default function Home() {
return (
<div>
<h2>Home</h2>
<Button variant="light" className="formButtons">
</div>
)
}
My App.css file looks like
.formButtons {
margin: 10;
overflow-wrap: break-word;
color: red;
}
I can tell it does not apply since the text color isn't red.
Thanks in advance!

First of all you need to import the Button element from react-bootstrap. You can write something like this:
import Button from 'react-bootstrap/Button'
After that, you can remove the className attribute because React Bootstrap builds the component classNames in a consistent way that you can rely on. You can base your styles on the variant attribute, so try something like this:
Home.js
import React from "react";
import Button from 'react-bootstrap/Button'
import '../App.css'; // Reflects the directory structure
export default function Home() {
return (
<div>
<h2>Home</h2>
<Button variant="light">TEXT</Button>
</div>
)
}
App.css
.btn-light {
margin: 10;
overflow-wrap: break-word;
color: red;
}

Related

Hover Material UI Icon and Text

I am working on a React JS Project. I was making something like a breadcrumb where there is a text and an icon. I am using material UI icon.
import UpdateIcon from "#material-ui/icons/Update";
import styles from " myfile.module.css "
<div className={styles.headItem}>
<UpdateIcon
className={classes.bread}
/>
<h1
className={styles.bread}
>
Bread Text
</h1>
</div>
Problem : I want to set the hover of this icon + text. But I have module file for normal html elements and material UI makestyles for materia UI items.
So I can't set the hover of whole. I tried setting the headItem class but it is not working
I would suggest to make some changes, the first one is that I prefer to import the css styles like this, because you can use the classes as regular strings
import "./styles.css";
Suppose that your styles.css have this class that is just applying the regular styles for your breadcrumb.
.head {
text-decoration: underline;
text-transform: uppercase;
}
Then you can reference this class in your file:
import React from "react";
import UpdateIcon from "#material-ui/icons/Update";
import "./styles.css";
import { makeStyles } from "#material-ui/core";
const useStyles = makeStyles({
bread: {
"&:hover": {
color: "green"
}
}
});
export default function App() {
const classes = useStyles();
return (
<div className={`head ${classes.bread}`}>
<UpdateIcon />
<h1>Bread Text</h1>
</div>
);
}
Notice that we're referencing the css class that we have on the styles.css as a string, and then we just add the material ui class variable by using string interpolation. I have this sandbox where you can see the result:
https://codesandbox.io/s/still-pine-0v2jw

How to test CSS properties defined inside a class with react testing library

I am trying to test CSS properties that i have defined inside a class in css, wing the react testing library. However I am unable to do so.
Adding the simplified snippets.
import React from "react";
import { render, screen } from "#testing-library/react";
import '#testing-library/jest-dom/extend-expect';
import styled from "styled-components";
const Title = styled.span`
display: none;
background: red;
`
test("testRender", () => {
render(
<div>
<Title>Test</Title>
</div>
)
const spanElement = screen.getByText("Test");
const elementStyle = window.getComputedStyle(spanElement);
expect(elementStyle.display).toBe('none');
});
The test fails at the expect statement. I have tried refactoring to traditional css, there also the test fails. In both cases, I have tested it manually and the styles are taking effect.
I also understand that we should not directly test CSS properties, but I have tried testing the visibility with toBeVisible(), but that only works if the display: none is directly entered as a style, and not as part of a class.
This should be a very simple thing, that works out of the box, but I have been at it for some time now, without any luck.
Any help is appreciated.
I agree with #ourmaninamsterdam answer.
In addition, for checking appearance or disappearance of any element, you can also use .not.toBeInTheDocument like so:
expect(screen.queryByText("Test")).not.toBeInTheDocument();
NOTE: You must use queryByText instead of getByText in this case since queryByText wont throw an error if it doesn't find the element (it will return null).
Official docs Reference - https://testing-library.com/docs/guide-disappearance#nottobeinthedocument
You can use expect(screen.getByText("Test")).not.toBeVisible();
import React from "react";
import { render, screen } from "#testing-library/react";
import "#testing-library/jest-dom/extend-expect";
import styled from "styled-components";
it("does display", () => {
const Title = styled.span`
display: block;
background: red;
`;
render(
<div>
<Title>Test</Title>
</div>
);
expect(screen.getByText("Test")).toBeVisible();
});
it("doesn't display", () => {
const Title = styled.span`
display: none;
background: red;
`;
render(
<div>
<Title>Test</Title>
</div>
);
expect(screen.getByText("Test")).not.toBeVisible();
});
...see the sandbox: https://codesandbox.io/s/blazing-river-l6rn6?file=/App.test.js

Adding CSS to react Component

I'm trying to add css to my newly created component. When I use inline styles it works. But when I try to import css from another separate file it doesn't work. Below I mention my 2 files.
Layouts.css
.Content {
margin-top: 16px;
}
Layouts.js
import React from 'react';
import Auxillary from './../../hoc/Auxillary'
import classes from './Layouts.css'
const Layout = (props) => (
<Auxillary>
<div>
Toolbar,Sidebar,Backdrop
</div>
<main className={classes.Content}>
{props.children}
</main>
</Auxillary>
);
export default Layout;
Have you tried making className='Content'
If you want to use classes.Content you must name your Layout css file like this
Layouts.module.css

CSS not changing when using React Router to route to another component

When I route my app to another component by using react-router-dom, the CSS doesn't change.
This is a minimalistic version of the code to demonstrate
App.js
import React from 'react';
import Home from './Home';
function App() {
return (
<div>
<Home></Home>
</div>
);
}
export default App;
Home.js
import React from 'react';
import './Home.css';
const Home = () => {
return (
<h1>Home</h1>
);
}
export default Home;
Home.css
body {
background-color: blue;
}
Dashboard.js
import React from 'react';
import './Dashboard.css';
import React from 'react';
import './Dashboard.css';
const Dashboard = () => {
return (
<div className='content'>
<h1>Dashboard</h1>
</div>
);
}
export default Dashboard;
Dashboard.css
.content {
display: flex;
align-content: center;
align-items: center;
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Dashboard from './Dashboard';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter as Router, Route } from 'react-router-dom';
ReactDOM.render(
<Router>
<div>
<Route exact path='/' component={App} />
<Route path='/dashboard' component={Dashboard} />
</div>
</Router>, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: ...
serviceWorker.unregister();
When I do /dashboard, it loads the Dashboard component, but it keeps the previous CSS that was loaded from the Home component that resides the App component. The background stays blue. I want that when I route to another component because I changed the URL, it loads whatever CSS that new component has attached to it and gets rid of whatever CSS was before. Is that possible?
Edit: I have made an example in CodeSandbox to illustrate. It's a little different from the code above due to the limitations of the playground, but the functionality is the same.
From what can be seen, importing as a module ends up importing it globally. If we comment the line import Home from "./Home"; the blue background disappears. Just importing the component, imports the whole CSS despite the CSS being imported in a modular way. I'm not sure if I am missing something.
Edit 2:
Here are the different solutions I tried:
CSS Modules, but the body style was still globally loaded.
Styled components don't let me modify the body or html selectors CSS. They require me to create a <div> element and
then have that element span the whole body which I would style
as if it was the body. Which is a workaround I don't want to use because for that I rather use CSS Modules for the whole body spanning .
Inline styling also doesn't let me modify the body or html selectors CSS. I would also need to use a workaround like a body spanning <div> as in Styled components.
The problem
When you import a css like you're doing here
import './Home.css';
you're importing it in a global scope, which means it will not disappear once imported.
The solutions
CSS Modules
What you want is either CSS Modules, which is used like this:
import styles from './Home.css';
<a className={styles.myStyleClass}>Hello</a>
Styled components
or a CSS-in-js framework such as styled components which is used like this:
import styled from 'styled-components';
const MyStyledElement = styled.a`
color: blue;
`;
<MyStyledElement>Hello</MyStyledElement>
Regular objects / inline styling
or just "regular" CSS-in-js like:
const myStyle = {
color: blue;
}
<a style={myStyle}>Hello</a>
There are plenty of options when it comes to styling, these alternatives are popular ones that I encourage you to explore and see which you enjoy.
After doing some more tests I have concluded that as of now it is not possible to change whatever CSS styles have been applied to a <body> or <html> selector in an React SPA when a CSS file is already loaded and one uses React Router to render other components. I still appreciate the answers and the time taken to help me find a solution. They are still valid answers if we are not talking about the <body> or <html> node in an HTML document. From them I learned about other ways to use CSS in React. I modified the original post with the solutions I tried.
What ended working was modifying the DOM styles with JavaScript whithin the component itself.
Home.js
import React from "react";
const Home = () => {
// Modify the DOM Styles with JavaScript
document.body.style.backgroundColor = "blue";
// Or uncomment below to modify the
// document root background color
// which in this case would be <html>
//document.bgColor = "blue";
// Or modify the root tag style of the document instead of the
// <body> (<html> in this case)
//document.documentElement.setAttribute('style', 'background-color: green');
return (
<div>
<h1>Home</h1>
<form action="/dashboard">
<input type="submit" value="Go to Dashboard" />
</form>
</div>
);
};
export default Home;
Here is a working example:
Where my app wasn't loading style sheets and the like. However, I was importing my assets directly into my index.html entry point.
By replacing the links with absolute paths as per this documentation, my problem was resolved.
For me, this meant changing
<head>
<link rel="stylesheet" href="./style.css" ></link>
</head>
to this:
<head>
<link rel="stylesheet" href="/style.css" ></link>
</head>
I'm not sure if the same thing would work for your import statements, but it is worth a shot.
More info: styles-not-working-with-react-router

In React, how to prevent a component's CSS import from applying to the entire app?

I'm using facebook's create-react app for my application:
In my Login.js container, I am importing CSS like so:
import React from 'react';
import '../../styles/users/Login.css'
const Login = () => {
....
The problem is the Login.css styles are being applied to my entire application... for example, if Login.css has:
body {
background:Red ;
}
The entire app would have a body of background: Red; Even outside of the Login container.
What I expected/want is for a CSS import within a container to only apply to that particular container.
Is that possible w React? How are react developers supposed to handle container specific stylings? Do I need to add an ID to all containers and include that in the entire CSS file?
1. Solution: Give your DOM elements class names to use them in your css.
JS:
// in Link.js
import React from 'react';
import '../../styles/Link.css'
const Link = ({children, href}) => (
<a className="link" href={href}>{children}</a>
);
CSS:
// Link.css
.link {
color: red;
}
2. Solution: Inline styles.
JS:
// in Link.js
import React from 'react';
import '../../styles/Link.css'
const Link = ({children, href}) => (
<a style={color: 'red'} href={href}>{children}</a>
);
3. Solution: CSS in JS.
There are some libraries that try to solve the styling issue:
Watch this talk: https://speakerdeck.com/vjeux/react-css-in-js
And have a look at this: https://github.com/cssinjs
styled-components: https://github.com/styled-components/styled-components
The best and easiest solution is to give classNames to every element you have in your code. I had the same issue when trying to apply widths and heights to my images and eventually found out that it was affecting whole app.

Resources