Why inline CSS is not working on component in react? - css

I'm using a component in react.
import style from "../../Style/Styles.module.scss";
const Anchor = (props) => {
return <a className={style["anchorTags"]} href={props.href}>{props.title}</a>;
};
export default Anchor;
where I have already written CSS for this component in my SCSS file.
.anchorTags {
border: 2px solid $Very-Light-Gray;
color: $Very-Light-Gray;
}
but when I'm writing inline css in a component when using this on another component it is not working.
import style from "../../Style/Styles.module.scss";
import Anchor from "./achortag";
<Anchor
style={{ paddingBlock: "0.7em", paddingInline: "2em" }}
href="/viewPlan"
title="VIEW PLANS"
/>
Please share your suggestion on how this will work?

In Anchor component:
const Anchor = (props) => {
return (
<a className={style.anchorTags} href="#" style={props.style}>
{props.title}
</a>
);
};
export default Anchor;
or use the spread operator, this will add any additional attributes:
const Anchor = (props) => {
return (
<a className={style.anchorTags} href="#" {...props}>
{props.title}
</a>
);
};
export default Anchor;

To use the desired style, you must use this syntax:
import style from "../../Style/Styles.module.scss";
const Anchor = (props) => (
<a className={style.anchorTags} href={props.href} {...props}>{props.title}</a>;
);
export default Anchor;
For more information, you can read this (Adding a CSS Modules Stylesheet).

Related

React component not rendering inline CSS

I am trying to write a react application where the App component renders an array of components to the screen. But the inline CSS are not showing up.
//App component
import data from "./data.js"
import Item from "./Item"
export default function App(){
const cardElements = data.map(item => <Item/>)
return (<div className='app'>
{cardElements}
</div>);
}
//Item component
export default function Item(){
const customStyle = {border: "2px solid black"};
return (<div style={customStyle} >Item component</div>);
}
The inline CSS in the Item component does not reflect on the webpage.
As you can see in the snippet below the inline style does indeed work. What is likely happening here is your style is bering overridden but we'd need more information to know for sure.
Sidenote: don't forget to add key prop when using .map in React.
const data = [1, 2, 3, 4];
function App() {
const cardElements = data.map(item => <Item key={item} />)
return (
<div className='app'>
{cardElements}
</div>
);
}
function Item() {
const customStyle = { border: "2px solid black" };
return <div style={customStyle}>Item component</div>;
}
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.js"></script>

Re-writing CSS in Styled-Components

I am currently working on a project which involves a dropdown menu, and I am following a tutorial. An issue that I encountered is with the dynamic styling of the dropdown.
<ul className={`dropdown ${dropdown ? "show" : ""}`}>
this is the code from the tutorial, my question is how can I rewrite it using styled-components?
// my Dropdown component
const Dropdown = ({ submenus, dropdown }) => {
return (
<StyledDropdown dropdown={dropdown}>
{submenus.map((submenu, index) => (
<li key={index}>
{submenu.title}
</li>
))}
</StyledDropdown>
);
};
export default Dropdown;
//styling of dropdown
export const StyledDropdown = styled.ul``;
You can get props in styled components
import styled, { css } from 'styled-components'
export const StyledDropdown = styled.ul`
${props => props.dropdown ? css`
// Style for show
` : ''}
`;

react toggling class, importing using module

i am trying to toggle a class with useState, but i imported the class using module (not globally, xxx.module.css).
is it possible to toggle the class without changing them to global?
example:
import styles from 'xxx.module.css'
function app(){
const [active, setActive] = useState(false);
return()
<div className={active ? "active" : " "}><p>Hy there!</p> </div>
<button onClick={() => setActive(!active)}>toggle me</button>
}
export default app
with a css
.active{
display: flex;
}
its something like that, but if i use module to import css it won't really work since it require {styles.active} (i've already tried changing the class name to {styles.active} its not really working).
is there any way to work around this? thanks!
My solution:
import s from './x.module.css'
import {useState} from 'react'
const App = () => {
const [active, setActive] = useState(false)
return (
<div>
<div className={active ? s.active : null}>Hi world!</div>
<button onClick={()=> setActive(!active)}>Activate!</button>
</div>
)
}
x.module.css:
.active {
color: black;
}
I personally use the classnames library for this:
const className = classnames({ [styles.active]: active });
Alternatively, you can set up the functionality yourself:
const className = active ? styles.active : undefined;
and then: <div className={className}>
You must use className as styles.active and it must not be between quotation marks.
So your division tag must like that:
<div className={active ? styles.active : " "}>
...some JSX...
</div>
PS: The code you write here to specifing the problem have full of errors. I don't think in real code you did this terrible mistakes but I want to indicate this stiutaion.

Dynamic CSS in CSS Modules when coming from Styled Components

The following question came up when I wanted to migrate from Styled Components to CSS Modules.
Let's say I have the following styled component which accepts a dynamic parameter offset and a dynamic CSS string theme:
const Li = styled.li`
&.selected {
background-color: grey;
}
margin-left: ${({ offset }) => offset}px;
${({ theme }) => theme};
`;
In my code, I'd use it the following way:
const Parent = () => (
<List>
{list.map((item) => (
<Item
key={item.id}
id={item.id}
selectedIds={[]}
offset={24}
theme={`
&.selected {
background-color: green;
}
`}
>
{item.name}
</Item>
))}
</List>
);
const Item = ({ id, offset = 0, theme, children }) => {
return (
<Li
theme={theme}
offset={offset}
className={selectedIds.includes(id) && 'selected'}
>
{children}
</Li>
);
};
Requirement: Now I would really keep the Item's component API: passing a number offset and a style string theme. So essentially everything in Parent component should stay this way.
How can I convert the Item component internally to use CSS Modules instead of the styled Li component?
It's probably a different way of thinking than you used to but it can work
You can use css variable
style={{ [`--offset`]: `${offset}px` }}
.item {
margin-left: var(--offset);
}
You can have a css module (file) dedicated to themes. In your case, it has withSelected
.withSelected {
&.selected {
background-color: green;
}
}
So you could pass it as "theme"
theme={themes.withSelected}
This is how the components look
import styles from "./style.module.scss";
import themes from "./themes.module.scss";
const Parent = () => (
<ul>
{list.map((item) => (
<Item
key={item.id}
id={item.id}
selectedIds={[1]}
offset={24}
theme={themes.withSelected}
>
{item.name}
</Item>
))}
</ul>
);
const Item = ({ id, offset = 0, theme, children, selectedIds }) => {
return (
<li
className={`${styles.item} ${theme} ${
selectedIds.includes(id) && themes.selected
}`}
theme={theme}
style={{ [`--offset`]: `${offset}px` }}
>
{children}
</li>
);
};
Demo: https://codesandbox.io/s/styledcomponent-to-css-modules-1kbqx
With 1 I'd concur with #Mosh to just use the style prop. Css modules are static by design and there no way to get this done otherwise (I think that styled-components also uses the style prop so you're not losing anything).
For 2 you can leverage Sass modules which allow you to define your theme in a single place and import them as required:
/theme/_colors.scss
$red: rgb(200, 0 50);
/components/Item.module.scss
#import "../theme/colors"
.selected {
background: $red;
}
Note: if you use Create React App absolute paths you can import from root as ~theme/colors

Button with image using React Typescript

I am using React Typescript.
How do I add image to my button?
I tried doing it and there are no errors, but I am getting a blank button.
How do I style my button element using Emotion CSS here?
import React from "react";
function PostButton(props){
let style = {
width:24,
height:24,
src: "../images/abc.png"
};
return(
<button style={style} onClick={() => props.handleClick()}>{props.label}</button>
);
}
return (
<div style={style}>
<PostButton src={"../images/abc.png"} handleClick = {props.incrementScore}/>
</div>
);
}
src would be background:url(../images/abc.png)
Perhaps you're confusing the src prop that an img HTML element would have?
Perhaps you should include a nested img component inside your button.
Working example: https://stackblitz.com/edit/react-emotion-hello-u9qyaa
Damian's answer is technically correct however if you're using webpack you'll need to import the image like this:
import abc from "../images/abc.png";
And use it like this:
function PostButton(props){
let style = {
width:24,
height:24,
background: `url(${abc})`,
};
return(
<button style={style} onClick={() => props.handleClick()}>{props.label}</button>
);
}

Resources