styled-component generate custom css class - reactjs

I have a question about the styled-components library. I know that this may not be an idiomatic way to do things, but I am curious if there is a styled-component method that can return a CSS class name. I would then be able to pass that class name into components that I render. This way, I can reuse some CSS. Then again, maybe this defeats the purpose of having isolated styled scoped to a single component.
For example, is there a function like generateCss?
const Button = styled.div`
background-color: blue;
`
const myCssClassName = styled.generateCss`
background-color: blue;
`
...
<Button className={myCssClassName} />

No, this is not possible. The whole idea of styled-components is to return new components. And if you want to create classes you should have a look at glamor or aphrodite. And here is a link to a discussion on github.

If you want to customize an existing styled component, you can use the .extend() API.
For example:
const Button = styled.div`
background-color: red;
`;
const BlueButton = Button.extend`
background-color: blue;
`;
export default () => (
<BlueButton />
);

Related

How to focus trap with styled-components? How to access classname from styled-components?

I'm currently using styled-components 5.0.1 with React. https://styled-components.com/
For context, my goal is to focus trap within a modal.
My problem is that classnames are randomly generated from styled-components so I'm not able to access these DOM nodes with querySelector. My other problem is that I'm not able to use React ref forwarding since I would have to do a lot of ref forwarding between component trees.
Is there a way to access the classname that is generated from styled-components? If so, I can use querySelector and go about the usual way of focus trapping by accessing the DOM nodes through querySelector.
Firstly, your component should be able to process the passed-in css:
import styled from "styled-components";
const Box = styled.div`
color: red;
${props => props.addCSS}
`;
const DatePicker = () => <Box>DatePicker</Box>;
Secondly, declare the css style.
import { css } from "styled-components";
const myCSS = css`
font-size: 60px;
`;
Lastly, pass it down to the child component.
<DatePicker addCSS={myCSS} />
I was able to solve this issue by accessing the DOM nodes with using a data- attribute.
For example,
const myComponent = styled.div`
// ...styles here
`;
const foo = () => (
<myComponent
data-foo-bar="foobar"
/>
);
console.log(document.querySelector('[data-a11y-id="HeaderNavBar-SearchButton"]');
// returns the DOM element for myComponent

React styled-components not applying styles to components

I'm trying to get used to styled-components in react. But it doesn't seem to work all the time. I'm currently using it in a project. While it works perfectly in some components, it doesn't apply the styles in some others.
Here's my code where it doesn't work.
I created the styles-components in a separate file (card.js) and folder (styles) and exported them like so;
import styled from 'styled-components/macro';
export const Title = styled.p`
font-size: 24px;
color: #e5e5e5;
font-weight: bold;
margin-left: 56px;
margin-right: 56px;
margin-top: 0;
`;
... (other components created the same way)
I then imported them in a file (index.js), in the same folder as the styles folder, containing the card.js file, where I used them like so;
import React from 'react';
import {Title, (some other components) } from './styles/card';
export default function Card({ children, ...restProps }) {
return <Container {...restProps}>{children}</Container>
}
Card.Title = function CardTitle({ children, ...restProps }) {
return <Title {...restProps}>{children}</Title>;
};
I then
I used the same method in all other styled-components files, but it doesn't work here. I'd like to know the cause, or if there's a better method of using styled-components.
Figured it out! React styled-components works perfectly when applied correctly. The problem was a typo error in my code.
I wrote
&{Picture}
when calling an earlier declared styled component instead of
${Picture}

How can I setup SCSS files (ViewEncapsulated way) in 'react app 2' like Angular component specific SCSS?

I installed 'react app 2' as well as node-sass. It's working fine with SCSS. But I just want to know how can I create component specific SCSS like Angular (that will never be a conflict with other components SCSS)
Angular automatically add an attribute for ViewEncapsulation see below example
In angular, there is an option for
encapsulation: ViewEncapsulation.None (Use to disable CSS Encapsulation for this component)
enter link description here
I know the question is old, but it has no answer, thus I want to share this article. Alsomst does the trick, with the exception that it seems to does not have support for something like ::ng-deep
React doesn't have native component styles like Angular does because it aims to keep away from any functionality that could easily be handled by third-party packages. So you have two pretty simple options:
Use styled-components to create component-specific styles. This is a pretty straightforward package that allows you to define styles for each element within a component and you can even pass variables into the styles. It generates internal CSS (kept in <style> tags in the document head) which will take precedence over external styles by default. Example:
// MainComponent.jsx
import React from 'react';
import styled from 'styled-components';
const Title = styled.h1`
color: red
`
const MainComponent = (props) => <Title>Hello World</Title>
In each of your components, add a class or ID to the root element so that you can simply add that selector to the beginning of your SCSS to only style that specific component. Example:
// MainComponent.jsx
import React from 'react';
const MainComponent = (props) => (
<div className="main-component">
<h1>Hello World</h1>
</div>
)
// MainComponent.scss
.main-component {
h1 {
color: red;
}
}
Now only h1 elements in your MainComponent will be red.
//JS
import React from "react";
import "./yourComponentName.scss";
export default props => {
const { className, children, ...restOperator } = props;
return (
<a className={`yourComponentName ${className}` } {...restOperator}>
{children}
</a>
);
}
//yourComponentName.scss
.yourComponentName{
position:relative;
background:red;
/* your property and value use nesting*/
ul {
margin: 0;
padding: 0;
list-style: none;
}
li { display: inline-block; }
a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
}

Override styled-components in React

I'm trying to find a way to override a styled component with styled-components like this:
Let's say I have a reusable component Wrapper:
class Wrapper extends Component {
...
render() {
const Wrap = styled.div`
padding: 5px;
background-color: green;
`;
return (
<Wrap>
{children}
</Wrap>
)
}
}
export default Wrapper
And then I have Component B that imports Wrapper but should extend the styles like this: myNewWrap uses Wrapper
import Wrapper from './Wrapper'
class B extends Component {
...
render() {
const myNewWrap = styled(Wrapper)`
background-color: red;
`;
return (
<myNewWrap>
Some awesome text
</myNewWrap>
)
}
}
Result should be that Some awesome text has padding from Wrapper but background-color from own component. But what I get is only the styles from Wrapper.
Have you considered using extend from Styled-Components? Styled generates new component styles with a new class whereas extend is meant to use base styling from another Styled component, but then tweak or add additional styles.
Additionally, their docs explain when you should you use styled() (see section "When should I use styled()?")
when to use styled
you override the styled component simply by passing a className to the styled component and do styling with reference to that class
<myNewWrap className="my-wrap">

Target specific CSS classes with Styled Components

How would I go about styling something like the react-datepicker with styled-components? The datepicker library looks like it uses some type of BEM style (screenshot below) which I would normally just use their provided class names and style those using Sass. But, how would I target those class names with styled-components? Is that even possible?
Since styled-components is just CSS™ you'd do it like with any other style sheet, by using the class names react-datepicker provided.
The only difference is that you'll have to wrap the datepicker in one wrapper styled component which applies all of these classes:
const Wrapper = styled.div`
&.react-datepicker {
color: blue;
}
`
<Wrapper>
<Datepicker />
</Wrapper>
Searching for hours, I found that the best solution is to add a stylized parent component (it can be a div) overlying the component that needs a className and add the definition of the className directly into the stylized parent component.
VERY IMPORTANT:
A space is needed between the ampersand & and the class for this to take effect!
const StyledParent = styled.div`
& .your-class-name {
border-color: red;
}
`;
<StyledParent>
<Datepicker yourClassName="your-class-name" />
</StyledParent>
If you ever need to access and style another component you can do this if they are not in the same file:
Export whatever you need to access:
export { Wrapper as CircledButtonWrapper };
Import it where you need it:
import { CircledButtonWrapper } from "/Bla/CircledButton";
Use it where you need to style it:
const Wrapper = styled.div`
/* Some other styles */
&:hover {
${CircledButtonWrapper} {
opacity: 1;
}
} `;
Edit:
I see now that the question was refering to accessing className...

Resources