I have a react component that is wrapped up in div:
AccountLogin.jsx:
import './AccountLogin.css';
export default observer(() => (
<div className="content">
Something here
</div>
));
AccountLogin.css:
.content {
color: blue;
background-color: blue;
margin: 500px;
}
But the css doesn't apply to my rendered component AccountLogin.
Any ideas why that could happen?
Looking at rfx-stack source, I can see that files suffixed with .global.css are imported in global scope where as others are imported as css-modules.
So you can either rename your file to AccountLogin.global.css or use the imported class name:
import styles from './AccountLogin.css';
Within component:
<div className={styles.content}>...</div>
Related
I am following these docs in order to style a material ui component (Paper) within a component (Menu) I am using.
I am using CSS modules to style my components (with Webpack as a bundler) :
// menu.js
import React from 'react';
import { StyledEngineProvider } from '#mui/material/styles';
...
import styles from './styles.module.css';
import Menu from '#mui/material/Menu';
import MenuItem from '#mui/material/MenuItem';
const MyMenu = (props) => {
...
return (
<StyledEngineProvider injectFirst>
<div id="my-menu">
<Button id="button-react-component" onClick={handleClick}>
My Menu
</Button>
<Menu
id="menu-react-component"
...
className={styles.menu}
>
<MenuItem ...>
<span> Example 1 <span>
</MenuItem>
</Menu>
</div>
);
}
// styles.module.css
.menu {
color: white;
}
.menu .MuiPaper-root {
background-color: red
}
// Also tried :
.menu .root {
background-color: red
}
My goal is to have the MuiPaper component have a given background-color. MuiPaper is a component that comes from the Menu component, but I am not using MuiPaper directly as I am only declaring the parent (<Menu>).
Ideally I want to use .css files for styling. I use webpack to bundle my css files into modules.
Here's what I see in my browser :
Notice how the background-color "red" is not applied on that last screenshot.
Thanks :)
CSS modules can't override a style from another CSS module (or elsewhere). There's a few ways to get around this:
Add another class specifically for the .menu paper, e.g. .menuPaper, and add it via PaperProps on the Menu component:
.menuPaper {
background-color: blue;
}
<Menu
id="menu-react-component"
...
className={styles.menu}
PaperProps={{ className: styles.menuPaper }}
>
Add the :global selector to your css selector:
.menu :global .MuiPaper-root {
background-color: red;
}
CSS modules work by "modulifying" CSS classnames by adding a unique ID to the end of them. The :global selector can be used to disable this and preserve the classname instead.
The difference between these two methods is that if you had multiple Menu components in your MyMenu component, using the :global method would give all the Menu instances inside of MyMenu the same background. With the PaperProps method only specific Menus with PaperProps={{ className: styles.menuPaper }} would get the styles applied.
css-loaderdocs: https://github.com/webpack-contrib/css-loader#scope
MUI Menu docs: https://mui.com/api/menu/#props (also see Popover component)
I'm trying to set the background image of a div depending on the value of a component property, the background doesn't show, however it does show when I harcode the background-image property in the css file.
Here is the component code :
import React, { Component } from "react";
import "./Banner.css";
export default class Banner extends Component {
render() {
const style = {
backgroundImage: `url("${this.props.image}")`,
};
return (
<div className="banner" style={style}>
Chez vous, partout et ailleurs
</div>
);
}
}
Here is the Banner.css file:
.banner {
/* background-image: url("../assets/images/moutains.png"); */
background-size: cover;
height: 170px;
border-radius: 20px;
text-align: center;
vertical-align: middle;
line-height: 170px;
font-size: 2.5rem;
color: #fff;
}
In the parent component:
<Banner image="../assets/images/moutains.png" text="" />
EDIT: Complete code and assets here: https://github.com/musk-coding/kasa
codesandbox: https://codesandbox.io/s/github/musk-coding/kasa
Thanks in advance for your help
Since, you are trying to access the image directly in your Component using the inline CSS. You must move your image to the public folder.
CODESANDBOX LINK: https://codesandbox.io/s/image-relative-path-issue-orbkw?file=/src/components/Home.js
Code Changes:
export default class Home extends Component {
render() {
const imageURL = "./assets/images/island-waves.png";
return (
<div className="container">
<div className="slogan" style={{ backgroundImage: `url(${imageURL})` }}>
Chez vous, partout et ailleurs
</div>
<Gallery />
</div>
);
}
}
NOTE: From React Docs, you can see the ways to add images in Component. create-reac-app-images-docs. But since you want an inline CSS, in that case we have to move our assets folder into the public folder to make sure that the image is properly referenced with our component.
I'm new to styled-components and I'm bit confused.
Can we display something or add functionality to styled-compoentns.
OR styled-components is component that we can apply css only
styled-components is primarily intended to apply css.
So typically you would use wrapper components that provide the content and use the components obtained from styled-components for decoration.
Once in a while, I have found it useful to use the .attrs constructor to pass children when
the content is very specific to the component.
const ResourceMissingError= styled.div.attrs({
children: 'This resource could not be found'
})`color: red`;
render(<ResourceMissingError />);
Can we display something or add functionality to styled-components?
Yes, styled components are usable as any native component would be. So just as HTML's <button> can be used to display something, you can use a styled button to do so. See below.
Similarly, you can add functionality as you would in a native component, by listening to click events, for instance. The demo below "adds" functionality to the ColorfulButton by handling its click event.
See also how the color is passed as a prop to the ColorfulButton via mycolor="green":
const ColorfulButton = styled.button`
display: inline-block;
color: ${props => props.mycolor || "blue"};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 2px solid palevioletred;
border-radius: 3px;
display: block;
`;
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.state = { text: "Learn JavaScript (click me)", done: true }
}
handleClick = e => {
this.setState({...this.state, done: !this.state.done});
}
render() {
return (
<div>
<ColorfulButton onClick={this.handleClick} mycolor="green">{this.state.text}</ColorfulButton>
<br />
{this.state.done ? 'Yes' : 'No'}
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>
<div id="app"></div>
You can make a CSS file and import it in your different components like making class in CSS and use that class in your component as className="". Also, you can refer inline CSS like this way style={{}} make sure the properties name like font-size will be written in fontSize in React inline CSS. Every CSS property that have a dash in the middle of the property name, the dash will be removed and the next letter after dash will be capitalized and also the property value will be in double or single quotation.
I've set up a new project in React using Webpack, and wanted to give a try to Styled Components.
My index.js looks like this:
import React from "react"
import ReactDOM from "react-dom"
import Page from "./site/Page"
import styled from 'styled-components'
// Create a Title component that'll render an <h1> tag with some styles
const Title = styled.h1`
font-size: 1.5em;
text-align: center;
color: palevioletred;
`;
// Create a Wrapper component that'll render a <section> tag with some styles
const Wrapper = styled.section`
padding: 4em;
background: papayawhip;
`;
const Index = props => {
return (
<Page>
<Wrapper>
<Title>Test</Title>
</Wrapper>
</Page>);
};
ReactDOM.render(<Index/>, document.getElementById("app"))
The code outputted by styled-components on the HTML page looks fine but the <style> the on the head doesn't get added, resulting in no css style at all.
<section class="sc-bwzfXH gzMTbA">
<h1 class="sc-bdVaJa bzmvhR">Test</h1>
</section>
Does somebody have any suggestions?
Take a look at this API: CSSStyleSheet.insertRule().
Styled Components inserts empty style tags for hosting these dynamically injected styles.
I am following the official reactjs instructions to create a sample app. My node version is 6.9.0.
I created sample react app which is supposed to display a empty tic tac toe table according to the official website using following instructions:
npm install -g create-react-app
create-react-app my-app
cd my-app
changed to my-app directory
removed the default files inside the source directory as directed. Now
my index.js looks like this
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
Then I ran yarn start
But all I see is blank screen no tic tac toe table. And couple warnings in the console saying
Compiled with warnings.
./src/index.js
Line 1: 'React' is defined but never used no-unused-vars
Line 2: 'ReactDOM' is defined but never used no-unused-vars
Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
You missed last parts in steps 4 & 5:
Add a file named index.css in the src/ folder with this CSS code.
Add a file named index.js in the src/ folder with this JS code.
index.css
body {
font: 14px "Century Gothic", Futura, sans-serif;
margin: 20px;
}
ol, ul {
padding-left: 30px;
}
.board-row:after {
clear: both;
content: "";
display: table;
}
.status {
margin-bottom: 10px;
}
.square {
background: #fff;
border: 1px solid #999;
float: left;
font-size: 24px;
font-weight: bold;
line-height: 34px;
height: 34px;
margin-right: -1px;
margin-top: -1px;
padding: 0;
text-align: center;
width: 34px;
}
.square:focus {
outline: none;
}
.kbd-navigation .square:focus {
background: #ddd;
}
.game {
display: flex;
flex-direction: row;
}
.game-info {
margin-left: 20px;
}
index.js
class Square extends React.Component {
render() {
return (
<button className="square">
{/* TODO */}
</button>
);
}
}
class Board extends React.Component {
renderSquare(i) {
return <Square />;
}
render() {
const status = 'Next player: X';
return (
<div>
<div className="status">{status}</div>
<div className="board-row">
{this.renderSquare(0)}
{this.renderSquare(1)}
{this.renderSquare(2)}
</div>
<div className="board-row">
{this.renderSquare(3)}
{this.renderSquare(4)}
{this.renderSquare(5)}
</div>
<div className="board-row">
{this.renderSquare(6)}
{this.renderSquare(7)}
{this.renderSquare(8)}
</div>
</div>
);
}
}
class Game extends React.Component {
render() {
return (
<div className="game">
<div className="game-board">
<Board />
</div>
<div className="game-info">
<div>{/* status */}</div>
<ol>{/* TODO */}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);
You should create some component/element/, maybe style it, then call ReactDOM to render your component to the underlying html and then you will have it.
React is used to handle JSX and creation of React component
ReactDOM in your simple case will be used to render created element to dom.
See here : https://reactjs.org/blog/2015/10/01/react-render-and-top-level-api.html
So ading something like
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
to your code, you will get something if in your index.html there is element with id="root" inside <body> tag
This simply means your project has eslint configured to catch unused variables.
If you use JSX or anything React within that file the warning will go away just like suggested by zmii in his answer.
But i am writing this answer because someone showed me their code and they were facing the same problem.
Their code :
import React from 'react';
const person = () => {
return "<h2>I am a person!</h2>"
};
export default person;
The problem in the above code was that while returning, he used double quotes. So instead of JSX, it was returning string and therefore they were getting error that React was never not used.
Conclusion: Syntax are important so keep in mind, specially if you are starting out.
Hope this helps someone.
ESlint needs to be configured to work with React JSX. This excellent article has all the details.