How can I set background image by dynamic names with styled-component? - css

I'm trying to set background-image with styled component. In the code below, I want to set background image with different divs, with img_01, img_02, img_03, .....
I saw many cases importing img path and use that, but I want to use dynamic name depending on the variable. Do I need to import all the images and set each of them?
import styled, { css } from 'styled-components';
const Div1 = styled.div`
width: ${props => props.width};
background: url('asset/images/img_0${props=>props.num}.png');
`;
class Main extends Component {
render() {
return (
<div>
<Div1 width={"475px"} num={1}>
</Div1>
<Div1 width={"154px"} num={2}>
</Div1>
</div>
)
}
}
How Can I do that without importing all ?

You can write it like that :
const Div1 = styled.div`
width: ${props => props.width};
background-image: ${props => `url('asset/images/img_0${props.num}.png')`};
`;

Related

How do I turn this CSS code into Styled-Components?

//ReactJS
import '/styling.css'
const Page = () =>{
return( <div className="Search-box"><input className="Text"></input><div>)
}
export default Page;
//CSS
.Search-box{box-radius:40px;}
.Search-box:hover > .Text{ padding:10px;}
You could probably achieve what you need with something like the below, but you will have to adjust according to your needs. You might have to consider if the components you are building can be reused and check different patterns of using this library.
Their documentation is well organized and intuitive. You should check it out:
https://styled-components.com/docs/basics
import styled from 'styled-components';
const StyledPageCotainer = styled.div`
border-radius: 40px;
&:hover > .Text {
padding: 10px
}
`;
const Page = () => (
<StyledPageContainer className="Search-box">
<input className="Text" />
</StyledPageContainer>
);
export default Page;

How to conditionally render using object properties in styled-components?

I am trying to conditonally render in styled-components. This code seems to work in this case.
background-color: ${props => (props.active ? 'Black' : 'Green')};
I want to rather use object properties from a JSON file and provide 2 colours to the above condition. Something similar to these below instead of Black and Green.
${colors['Brand/PrimaryBlack']}
${colors['Brand/PrimaryGreen']}
colored.json
{
"colors": {
"Brand/PrimaryBlack": "#424449",
"Brand/PrimaryGreen": "#8ED6C9",
}
}
styles.js
import styled from 'styled-components'
import { colors } from './colored.json'
const Tabs = styled.button`
background-color: ${props => (props.active ? 'Black' : 'Green')};
`
How can I achieve this?
The ternary works exactly the same as your previous code, but just references the keys in your colors JSON, i.e. background-color: ${props => colors[props.active ? "Brand/PrimaryBlack" : "Brand/PrimaryGreen"]};.
{
"colors": {
"Brand/PrimaryBlack": "#424449",
"Brand/PrimaryGreen": "#8ED6C9",
}
}
import styled from 'styled-components'
import { colors } from './colored.json'
const Tabs = styled.button`
background-color: ${props => colors[props.active ? "Brand/PrimaryBlack" : "Brand/PrimaryGreen"]};
`;
You can do what you desire using styled components in the following way:
background-color: ${(props) =>
props.active ? colors["Brand/PrimaryGreen"] : colors["Brand/PrimaryBlack"]};
Find the working CodeSandBox here
Inside of Template literal you pass any valid JavaScript code inside of ${} expression even call to function so if you have an object which you want to access some keys you can just access those keys as you would do in a normal JavaScript code. so if you have an object colors with some properties you can access it inside of you Styled Component like this
const colors = {
"Brand/PrimaryGreen": "green",
"Brand/PrimaryBlack": "black"
};
const Comp = styled.div`
background: ${props => props.active? colors["Brand/PrimaryBlack"] : colors["Brand/PrimaryGreen"]};
color: #fff;
`;
You can simply do this
<TagName active={this.state.active}>Test</TagName>
And in your styles something like this:
const TagName = styled.button`
width: 100%;
outline: 0;
border: 0;
height: 100%;
justify-content: center;
align-items: center;
line-height: 0.2;
${({ active }) => active && `
background: blue;
`}
`;

Increase size of Twemoji in REACT

My REACT component's code is like this
import React from 'react';
import { Twemoji } from 'react-emoji-render';
import emoji.css;
const emoji = () => {
return ( <Twemoji className="Twemoji" text=":+1:"/> );
}
export default emoji;
My css file (emoji.css) has the following code
.Twemoji {
width: 20em;
height: 20em;
}
but the size of the emoji doesn't change.
if I inspect the element and modify the inline style in the page html that works
Please can you help me understand how I can increase the emoji size via CSS
Twemoji Component does not take a prop className (see here), instead you will have to use the options prop in order to pass a custom css classname
const options = { className: "Twemoji" };
const emoji = () => {
return ( <Twemoji text=":+1:" options={options} /> );
}
EDIT:
you would also have to add !important to width and height in the css class to take precedence over the element style (see css precedence)
.Twemoji {
width: 4em !important;
height: 4em !important;
}

gatsby-image: how to import the processed image into css and use it with background-image property

I sucessfully implemented the gatsby-image into my project and replace lots of img tag that are used in my components. But now im trying to optimized the background image for some of my component but i dont know how since using gatsby-image would generate a new img tag, and i cant use that to style as a background for say a div element. can s1 show me how i can use the generated images with css. Here's my code:
const HeaderlineSection = ({headerOne}) => {
return(
<div className="header-back" ></div>
)
}
export const query = graphql`
query IndexPageQuery {
headerOne: imageSharp(id: { regex: "/header_one.jpg/" }) {
sizes(maxWidth: 1200 ) {
...GatsbyImageSharpSizes
}
}
}
previously, in my css i use a non optimized image for backgroud-image:
.header-back {
background: url(../images/header_one.jpg) 50% 0 no-repeat;
height: 470px;
width: 100%;
}
I am using gatsby-background-image plugin for that. Here is one exemple of how you can use it :
import React from 'react'
import { graphql, StaticQuery } from 'gatsby'
import styled from 'styled-components'
import BackgroundImage from 'gatsby-background-image'
const BackgroundSection = ({ className }) => (
<StaticQuery query={graphql`
query {
desktop: file(relativePath: { eq: "seamless-bg-desktop.jpg" }) {
childImageSharp {
fluid(quality: 100, maxWidth: 4160) {
...GatsbyImageSharpFluid_withWebp
}
}
}
}
`}
render={data => {
const imageData = data.desktop.childImageSharp.fluid
return (
<BackgroundImage Tag="section"
className={className}
fluid={imageData}
backgroundColor={`#040e18`}
>
<h1>Hello gatsby-background-image</h1>
</BackgroundImage>
)
}
}
/>
)
const StyledBackgroundSection = styled(BackgroundSection)`
width: 100%;
background-repeat: repeat-y;
`
export default StyledBackgroundSection
The code is self-explanatory, but basically, element will be replaced with the element that you select in the Tag attribute and will have the background image set to the one selected with the graphql imageSharp query.

Apply same styling on multiple elements in component

const GreenRow = styled.div`
background-color: green;
`
const RedRow = styled.div`
background-color: red;
`
const YellowRow = styled.div`
background-color: yellow;
`
const GreyRow = styled.div`
background-color: grey;
`
const MyComponent = () =>
<div>
<GreenRow>Green row</GreenRow>
<div>Blue row</div>
<RedRow>Red row</RedRow>
<YellowRow>Yellow row</YellowRow>
<GreyRow>Grey row</GreyRow>
</div>
I'm using styled-components to style elements in a component.
I want to apply a repeated styling (e.g. font-weight) on some elements in a component. Some of these component are already styled with styled-component, so this would be some kind of "second dimension" styling.
For example, if I could define styling with a certain classname, I could then apply that classname to each of those elements. But as I've understood, styled-components don't return any classname. And I don't want to start defining styles in other files than the component itself.
Another thought is to render styling with styled-component's css library (see code below) and include it in every applicable styled-component definition. But then I would need to convert some elements to styled-components just for this purpose (as they aren't styled otherwise).
const FontWeight = css`
font-weight: 600;
`
What would be the most succinct way to apply this "second dimension" styling?
You can interpolate a function into the template literal, which gets passed the props of the component with ${props => props.component_name && css ... }.
In the following, I hook into Row and add some additional styling for Green:
import styled, { css } from styled-components
const Row = styled.div`
/* Generic row styling */
font-weight: 600;
/* Unique row styling */
${props => props.Green && css`
background: green;
`}
`
Note that you'll additionally need to import css!
Now all you have to do is render the row with the additional property when you want a green one:
render(
<div>
<Row>Normal Row</Row>
<Row Green>Green Row</Row>
</div>
);
The green row will inherit all of the styling of the regular rows, and also inherit the rules that are unique to that specific element.
Hope this helps!

Resources