React Styled component: how to add css styles based on props? - javascript

I've been trying to find the solution to my problem.
I have several Heading Tags (H1, H2 etc) each in their own file.
I would like to add some css when calling them based on a prop. Some headings have a small border-bottom and some don't. So, in order to refractor my code, I want to add some css based on a prop. I can't seem to find a way.
Here's an example of Heading H2:
import styled from 'styled-components';
import colors from '../../../../colors';
import fonts from '../../../../fonts';
import fontWeights from '../../../../fontWeights';
const HeadingH2 = styled.h2`
color: ${colors.text};
font-family: ${fonts.montSerrat};
font-size: 1.6em;
font-weight: ${fontWeights.light};
letter-spacing: 0.2em;
padding-bottom: 0.7em;
position: relative;
text-transform: uppercase;
text-align: center;
&:after{
content: "";
display: block;
height: 3px;
width: 45px;
background-color: currentColor;
/* position */
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
}
`;
export default HeadingH2
Example of calling Heading H2:
import React from 'react';
import HeadingH2 from '../../common/headings/heading_h2';
import HeadingBaseline from '../../common/headings_baseline';
// Features
import {SectionContainer, FeaturesContainer} from './features.style';
import Feature from './feature';
import feature1 from '../../../img/features/feature1.png';
import feature2 from '../../../img/features/feature2.png';
import feature3 from '../../../img/features/feature3.png';
// Text
import Text from '../../../content';
const Features = () => {
return(
<SectionContainer id={"what"}>
<HeadingH2>
What We Do
</HeadingH2>
<HeadingBaseline>
{Text.headingBaseline}
</HeadingBaseline>
<FeaturesContainer>
<Feature
src={feature1}
headingText={Text.feature1.heading}
paragraph={Text.feature1.paragraph}
/>
<Feature
src={feature2}
headingText={Text.feature2.heading}
paragraph={Text.feature2.paragraph}
/>
<Feature
src={feature3}
headingText={Text.feature3.heading}
paragraph={Text.feature3.paragraph}
/>
</FeaturesContainer>
</SectionContainer>
)
};
export default Features;
I want to extract the following CSS properties
position: relative;
text-transform: uppercase;
text-align: center;
&:after{
content: "";
display: block;
height: 3px;
width: 45px;
background-color: currentColor;
/* position */
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
So, assuming I have the above CSS rule in a separate file, how do I add/import them using props on my styled component HeadingH2.
Thanks for the help :)

You can also use css helper from styled-components to create a SharedStyles.js file.
In the demo you can see it in action.
Just using it in a style of an inherited component is not working as expected. If I'm adding it to StyledBase then the variables are not correctly added afterwards (hover style override stops working).
That's why I copied ${borderBottom} to each styled component Heading1 / Heading2 instead of adding it to StyledBase.
I think having a level prop for the heading is a good idea but I would handle it differently by creating a HeadingBase component and add your styles to a StyledBase component (also see code in the demo).
The HeadingBase code looks like this:
const HeadingBase = ({ className, children, level = 1 }) =>
React.createElement(`h${level}`, { className }, children);
It's a component that renders h1,h2,... tags based on the prop level passed (defaults to h1). The h-tag receives className as props (needed for styled-components) and contains the children passed to the component.
SharedStyles.js
import { css } from "styled-components";
export const borderBottom = css`
&:after{
content: "";
display: block;
height: 3px;
width: 200px;
background-color: ${props => props.color || "black"};
/* position */
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
`;
Then you can import it with import { borderBottom } from "./SharedStyles"; and add it to your styled-component like following:
const Heading1= styled.h1`
${borderBottom}
`;

Something like this works:
const HeadingH2 = styled.h2`
position: ${props => props.relative && 'relative'};
padding: ${props => props.paddingBottom ? '0 0 20px 0' : '0'};
}
`;
Then use like this:
<HeadingH2 relative paddingBottom />

Possible answer:
I add the following CSS rules in a separate file like so.
I create a function which returns a string of text. I can import this function and add those rules to any component I wish.
export const borderBottom = () => {
return `
position: relative;
text-transform: uppercase;
text-align: center;
&:after{
content: "";
display: block;
height: 3px;
width: 45px;
background-color: currentColor;
/* position */
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
}
`
}
And use it like so on any heading or component that I wish:
import styled from 'styled-components';
import colors from '../../../../colors';
import fonts from '../../../../fonts';
import fontWeights from '../../../../fontWeights';
import {borderBottom} from '../../../../css';
const HeadingH5 = styled.h5`
color: ${colors.black};
font-family: ${fonts.montSerrat};
font-size: 1em;
font-weight: ${fontWeights.light};
letter-spacing: 0.1em;
padding-bottom: 0.45em;
margin-bottom: 25px;
${borderBottom}
`
;
export default HeadingH5;
This works for me. Any other suggestions are welcome.

You should definely check this: typestyle
the best way you can write dynamic css (for me). Works perfectly with react, even with ssr if you need it...

Why not just have a headingLevel prop? and then pass it into the styled component? And just have one StyledHeader styled component as I'm guessing the code is the mostly the same in all the heading styles files? Which is a big no no, you want to always try not to repeat your code.
const Features = () => {
return(
<SectionContainer id={"what"}>
<StyledHeader
headingLevel={headingLevel}
>
What We Do
</StyledHeader>
<HeadingBaseline>
{Text.headingBaseline}
</HeadingBaseline>
<FeaturesContainer>
<Feature
src={feature1}
headingText={Text.feature1.heading}
paragraph={Text.feature1.paragraph}
/>
<Feature
src={feature2}
headingText={Text.feature2.heading}
paragraph={Text.feature2.paragraph}
/>
<Feature
src={feature3}
headingText={Text.feature3.heading}
paragraph={Text.feature3.paragraph}
/>
</FeaturesContainer>
</SectionContainer>
)
};
export default Features;
And in your StyledHeader file
The below function will take your passed in heading level of h1, h2, h3 and will apply a border, if not the above 3 heading level it will be 0 value. I'd do some checks to ensure the value is lower case e.g. toLowerCase()
const getBorder = ({ headingLevel } ) => {
const headingLevelMap = {
h1: 0.7,
h2: 0.6,
h3: 0.6,
};
return headingLevelMap[headingLevel] || 0;
}
const HeadingH2 = styled.headingLevel`
color: ${colors.text};
font-family: ${fonts.montSerrat};
font-size: 1.6em;
font-weight: ${fontWeights.light};
letter-spacing: 0.2em;
padding-bottom: 0.7em;
border-bottom: ${getCorrectBorderBottom}em solid black
position: relative;
text-transform: uppercase;
text-align: center;
&:after{
content: "";
display: block;
height: 3px;
width: 45px;
background-color: currentColor;
/* position */
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
}
`;
I'd also check that if the value of the passed in headingLevel is not any of the 6 heading levels it should have a default value of whatever you want.
The above was just quick pseudo code, but hopefully get the general idea here? Let me know it comments if not.
I'd also recommend that you split your Title component out into a separate component.

Related

My components keep stacking on themselves when i try to reuse them

I want to use the components i made multiple times while rendering dynamic content
but when i try to render them they just stack up on themselves in the same position
whenever i render the component, multiple times, i dont even see the sliders and the >title stacks up on eachother
import React from "react";
import styled from "styled-components";
import ellipse from "../img/ellipse.png";
import Range from "./Range";
function RangeComp() {
const titlesArr = [
"Cybersecurity",
"Developer",
"DevOps",
"Designer",
"Project Manager",
"Product Manager",
"Marketer",
"Writer",
];
console.log(titlesArr);
return (
<Container>
<Circle />
<Heading>Score your level of interest in these job titles:</Heading>
<Divs>
<Div1>
<Range title={titlesArr[0]} />
<Range title={titlesArr[1]} />
</Div1>
<Div2></Div2>
</Divs>
</Container>
);
}
export default RangeComp;
const Container = styled.div`
position: absolute;
width: 980px;
height: 583px;
left: 650px;
top: 220px;
box-shadow: 0px 4px 29px #f0f3ff;
border-radius: 35px;
:hover {
border: 1px solid black;
}
`;
const Circle = styled.div`
position: absolute;
background-image: url(${ellipse});
width: 30px;
height: 30px;
right: 1.8%;
top: 2%;
background-repeat: no-repeat;
background-size: cover;
`;
const Heading = styled.div`
position: absolute;
width: 400px;
height: 31px;
font-family: "HelveticaNeueCyr";
font-style: normal;
font-weight: 400;
font-size: 20px;
line-height: 155.02%;
color: #30302e;
left: 8%;
top: 10%;
`;
const Divs = styled.div``;
const Div1 = styled.div``;
const Div2 = styled.div``;
Above is where i want to reuse the component but they just stack up on each other
Below is the component i want to reuse
import React, { useState } from "react";
import "./Range.css";
import styled from "styled-components";
import ReactSlider from "react-slider";
function Range(props) {
const [currentValue, setCurrentValue] = useState(0);
return (
<div className="range">
<ReactSlider
className="customSlider"
trackClassName="customSlider-track"
thumbClassName="customSlider-thumb"
marks={1}
min={0}
max={10}
defaultValue={0}
value={currentValue}
onChange={(value) => setCurrentValue(value)}
/>
<h4>{props.title}</h4>
<h1 className="range-value">{currentValue}/10</h1>
</div>
);
}
export default Range;
What's inside your Range.css?
If the position is:
position: absolute;
Then your components will always stack on top of each other because they all have the same style.
You might need to set the position to:
position: relative;
So that the components will position themselves relative to each other.

Invert two React component text colors when clicking on input tag

I am new to React and did not find any solution to this simple problem.
I want to revert LangText colors when the toggle button is clicked - initially ENG is white and EST is black and every time input is clicked the colors invert.
I have separate files for returning and styling components.
I tried to change the color of a variable (located on top of the style-components file) inside the styled component tag, so with CSS - inside Input pseudo-class &:checked + span. Looked surreal and didn't work in any way.
I would be very thankful for an example of how to change two colors at the same, time in this case. There are always too few examples with components, usually, CSS is used separately, but for me this method is more readable and logical.
import React from 'react'
import { Input, InputWrapper, Slider, ToggleContainer, LangText} from './LangugageToggleElements';
const LanguageToggle = ({onChange}) => {
return(
<ToggleContainer>
<InputWrapper>
<Input type="checkbox" onChange={onChange}/>
<Slider>
<LangText>ENG</LangText>
<LangText>EST</LangText>
</Slider>
</InputWrapper>
</ToggleContainer>
)} ;
export default LanguageToggle
import styled from "styled-components";
let toggleBackground = "#000";
let textColor = "#fff";
export const ToggleContainer = styled.div`
position: absolute;
top: 10px;
right: 20px;
`
export const InputWrapper = styled.label`
position: relative;
display: flex;
justify-content: center;
text-align: center;
`
export const Input = styled.input`
position: absolute;
left: -9999px;
top: -9999px;
&:checked + span {
&:before {
left: 52px;
}
}
`
export const Slider = styled.span`
display: flex;
justify-content: center;
text-align: center;
cursor: pointer;
width: 105px;
border-radius: 100px;
position: relative;
transition: background-color 0.2s;
color: ${textColor};
&:before {
content: "";
position: absolute;
top: 15px;
left: 2px;
width: 50px;
height: 20px;
border-radius: 45px;
transition: 0.2s;
background: ${toggleBackground};
box-shadow: 0 2px 4px 0 rgba(0, 35, 11, 0.2);
}
`;
export const LangText = styled.p`
padding-right: 5px;
padding-left: 5px;
z-index: 1;
letter-spacing: 3px;
`;
I think you can simply use a useState hook to maintain checkbox and the use it for your LangText.
<ToggleContainer>
<InputWrapper>
<Input type="checkbox" onChange={()=>{
onChange();
//use state hook to maitain the checkbox value
}}/>
<Slider>
<LangText className={isChecboxValue === x ? color : invert }>ENG</LangText>
<LangText className={isChecboxValue === y ? invert: color}>EST</LangText>
</Slider>
</InputWrapper>
</ToggleContainer>

Styled-components not exporting

Error:
./src/card.js
Attempted import error: 'Bottom' is not exported from './styles/cards.style'.
card.js
import React from 'react'
import {
Bottom,
Color,
Text,
Image
} from "./styles/cards.style";
function Card(props) {
return (
<div>
<Bottom>
<Color />
<Text>{props.text}</Text>
<Text>{props.text}</Text>
</Bottom>
<Image
alt=""
src={props.image}
/>
</div>
);
}
export default Card;
cards.style
import styled from "styled-components";
export default {
colors: {
black: "rgba(0,0,0,1)",
brandPrimary: "rgba(238,120,36,1)",
brandPrimaryLight: "rgba(255,184,8,1)",
brandTertiary: "rgba(0,65,125,1)",
darkSlateGray: "rgba(51,51,51,1)",
white: "rgba(255,255,255,1)"
},
fonts: {
uiMainContent: {
family: "Poppins",
size: "15px",
weight: "300",
lineHeight: "21px"
},
uiSubContent: {
family: "Poppins",
size: "13px",
weight: "300",
lineHeight: "20px"
}
}
};
export const Bottom = styled.div`
width: 100%;
height: calc(100% - 20px);
background-color: ${props => props.theme.colors.white};
border-radius: 4px;
padding: 0 0 20px;
display: flex;
flex-direction: column;
align-items: flex-start;
position: relative;
`;
export const Color = styled.div`
height: 120px;
background-color: ${props =>
props.theme.colors.brandPrimary};
margin-bottom: 16px;
border-radius: 4px 4px 0px 0px;
align-self: stretch;
`;
export const Text = styled.p`
color: ${props => props.theme.colors.black};
margin-left: 16px;
letter-spacing: 0.1px;
font-family: ${props =>
props.theme.fonts.uiSubContent.family};
font-size: ${props =>
props.theme.fonts.uiSubContent.size};
font-weight: ${props =>
props.theme.fonts.uiSubContent.weight};
line-height: ${props =>
props.theme.fonts.uiSubContent.lineHeight};
&:not(:last-of-type) {
margin-bottom: 4px;
}
`;
export const Image = styled.img`
width: 150px;
height: 92px;
position: absolute;
left: 29px;
top: 14px;
`;
I am trying to build cards in reactjs. I usually stick to scss however cannot use props with scss which I will have to use later to dynamically generate components. Not sure what is wrong here as I did export Button. Please can someone shed some insight you see what is so blatantly wrong it is causing this error.
in that case you have an export default as the first thing of you code, if you are exporting more than one thing from the same file, you should stick to exporting each const/function by itself and not having any export default
If you are using ReactJS/NextJS I would really recommend creating a global theme that you normally write and import with the application, so you could have things like
// global.js
const GlobalStyle = createGlobalStyle`
* {
box-sizing: border-box;
}
:root {
--black: rgba(0,0,0,1);
--brandPrimary: rgba(238,120,36,1);
...
...
`
}
Take a look here, it should help you a lot.

vue js scoped slots styles error with vue styled components

I tried using vue-styled-compoenents to style a simple button with some text inside but the styles dont work and I get a scopedSlots issue in the parent component.
This is the code for the button and the text components in component.js
import styled from 'vue-styled-components';
export const sLabel = styled.label`
color: #000;
`;
export const sButton = styled.div`
height: 1rem;
width: 2rem;
background-color: #000;
${sLabel} {
color: #fff;
}
`;
This is my code in my page.
<template>
<sButton>
<sLabel>Button</sLabel>
</sButton>
</template>
<script>
import { sButton, sLabel } from './component.js'
export default {
components: {
sButton,
sLabel
}
}
</script>
This is the result I get under the sButton styles and nothing under sLabel
), scopedSlots: this.$scopedSlots
But Instead if I just use this code it works.
export const sButton = styled.div`
height: 1rem;
width: 2rem;
background-color: #000;
label {
color: #fff;
}
`;
The styles are applied to the parent component if I declare the parent component before the child even if the styles are under the child.
export const sButton = styled.div`
height: 1rem;
width: 2rem;
background-color: #000;
${sLabel} {
color: #fff;
}
`;
export const sLabel = styled.label`
color: #000;
`;
Can someone tell me where my code is incorrect and what is causing these issues ?

How to import 2,3 object from another file in reactJS

I am beginner to ReactJS, Currently I am using styled-component for style some module. Actually I created 2 files in one folder. One is style.js where I am making 2,3 object and now I want to export these 3 object to my another file which name is 2nd.js but it not working for me Could you please help me How I can import style.js object to my file .
Style.js Code
import styled from 'styled-components';
export const SubText = styled.div`
font-size: 20px;
text-align: center;
padding-bottom: 30px;
width: 330px;
color: #012653;
margin: 0 auto;
font-weight: 440;
`;
export const GeneralText = styled.div`
color: red;
font-size: 26px;
font-weight: 600;
text-align: center;
min-width: 266px;
padding-bottom: 30px;
font-family: Lato, sans-serif;
margin-top: 50px;
color: #012653;
`;
export const ButtonWrapper = styled.div`
text-align: center;
margin-top: 26px;
`;
2nd.js Code
import Style from './Style';
<GeneralText>This is dummy text </GeneralText>
You can do this by:-
import {SubText, GeneralText, ButtonWrapper} from './style'
Actually,there are many ways to solve this:
import * as Style from './style'
Or the above answers says:
import {SubText, GeneralText, ButtonWrapper} from './style'

Categories