pass background url as prop to styled component - reactjs

I have the following code:
// #flow
import React from 'react';
import { Route } from 'react-router-dom';
import Split from '../../components/grouping/Split';
import CenterBox from '../../components/grouping/CenterBox';
import styled from 'styled-components';
type Props = {
routes: Array<Object>,
background: String
};
export default ({ routes, background }: Props) =>
(<div>
<Split push="right" alignItems="center" height={50} pad={{ horizontal: 20 }}>
<div />
<div>This feature will be available soon!</div>
</Split>
<DashboardContent background={background}>
<CenterBox>
<div style={{ transform: 'translateY(50%)' }}>
<CenterBox height={300} width={500} backgroundColor="#FFFFFF">
This feature is not included as part of the design beta and will be available soon
</CenterBox>
</div>
</CenterBox>
</DashboardContent>
</div>);
const DashboardContent = styled.div`
background: url(${props => props.background}) no-repeat top
center;
background-size: 100%;
min-height: 100vh;
`;
I would like to pass background as a prop to my styled component so that when it is passed a link to an image file it sets it as a background, the code compiles but the background does not show up. What am I doing wrong?

Changing your background property to be a function that returns a string will fix your issue.
background: ${props => `url(${props.background}) no-repeat top center`};

Is this going to work out fine?
const DashboardContent = styled.div`
background: url(${props => props.background}) no-repeat top center;
`
<DashboardContent background={`https://xxxx/xxxx${background}`}/>

This worked for me!
import styled from 'styled-components';
import img from './img/background.gif';
const Content = styled.div`
background-image: url(${img});
`;

Related

Can't style #mui Avatar icon with styled-components

I'm playing around with styled-components and having troubles working with material-ui. So thats the code:
import React from "react";
import styled from "styled-components";
import ChatIcon from "#mui/icons-material/Chat";
import MoreVertIcon from "#mui/icons-material/MoreVert";
import { Avatar} from "#mui/material";
function Sidebar() {
return (
<Container>
<Header>
<UserAvatar className={"override"} />
<IconsContainer>
<IconButton>
<ChatIcon />
</IconButton>
<IconButton>
<MoreVertIcon />
</IconButton>
</IconsContainer>
</Header>
</Container>
);
}
export default Sidebar;
const Container = styled.div``;
const Header = styled.div`
display: flex;
position: sticky;
top: 0;
background-color: white;
z-index: 1;
justify-content: space-between;
align-items: center;
padding: 15px;
height: 80px;
border-bottom: 1px solid whitesmoke;
`;
const UserAvatar = styled(Avatar)`
height: 60px;
`;
const IconsContainer = styled.div`;
The styled div is working completely fine, but when I import 'Avatar' from #mui and try to add some styling named UserAvatar, it is completely ignoring what I'm writing down.
I think that with mui they have their own version of styled for styled components. https://mui.com/system/styled/
It appears they want you to use it rather than styled-components
import Button from '#mui/material/Button';
import { styled } from '#mui/material/styles';
const CustomButton = styled(Button)({
// your custom styles go here
}) as typeof Button;
see the import from import { styled } from '#mui/material/styles';;

Adding .png Logo to my Navigation bar with react styled components

hello I am trying to start a beginner react project using react and styled components. I was following a tutorial that showed me how to import some stock react logos, but I can't figure out how to do it using my own image.
export const NavbarContainer = styled(Container)`
display: flex;
justify-content: space-between;
height: 80px;
${Container}
`;
export const NavLogo = styled(Link)`
color: #fff;
justify-self: flex-start;
cursor: pointer;
text-decoration: none;
font-size: 2rem;
display: flex;
align-items: center;
`
export const NavIcon = styled(Icon)`
margin-right: 0.5rem;
`
Below is the code for my navigation bar
import React from 'react';
import { Nav, NavbarContainer, NavLogo, NavIcon } from './Navbar.elements';
import { ReactComponent as Icon } from './icon.png';
const Navbar = () => {
return (
<>
<Nav>
<NavbarContainer>
<NavLogo to="/">
<NavIcon />
SKYPRECISION
</NavLogo>
</NavbarContainer>
</Nav>
</>
)
}
export default Navbar
You need to add an img tag like this
<img src={src} alt="My awesome logo" />
You can replace the NavIcon with that.
If you want that image to utilize styled-components you can do something like:
const MyImage = styled.img`
your css rules here
`
and use it in code
<NavLogo to="/">
<MyImage />
SKYPRECISION
</NavLogo>

How to EXTEND imported component styled components

I cannot extend my imported component. I was looking into styled components docs and find that in v4+ should works prop "as", but it doesnt.
COMPONENT:
type Props = {
padding: string,
justify: string
}
const FlexContainer = styled.div<Props>`
padding: ${props => props.padding};
display: flex;
flex-wrap: wrap;
justify-content: ${props => props.justify};
`
export const Flexcontainer: React.FC<Props> = props =>{
return (
<FlexContainer padding={props.padding} justify={props.justify}>
{props.children}
</FlexContainer>
)
}
EXTENDED STYLE:
import { Flexcontainer } from '../../reusable/FlexContainer';
const FlexContainerExtended = styled.div`
color: red;
`
USE:
<FlexContainerExtended
padding={null}
justify={"flex-start"}
as={Flexcontainer}>
You just have to add a prop className to your Flexcontainer component like this:
export const Flexcontainer: React.FC<Props> = props =>{
return (
<FlexContainer className={props.className} padding={props.padding} justify={props.justify} >
{props.children}
</FlexContainer>
)}
To override styles, styled-components passes a className as props to the overrided component, it's why
You can just pass the base component to the styled function to override it.
type Props = {
padding: string,
justify: string
}
const FlexContainer = styled.div<Props>`
padding: ${props => props.padding};
display: flex;
flex-wrap: wrap;
justify-content: ${props => props.justify};
`
const FlexContainerExtended = styled(FlexContainer)`
color: red;
`
export const Flexcontainer: React.FC<Props> = props =>{
return (
<FlexContainer padding={props.padding} justify={props.justify}>
{props.children}
</FlexContainer>
)
}
// And use it like this
<FlexContainerExtended
padding={null}
justify={"flex-start"}/>
I know this question was asked a long time ago, but I leave here the solution I found for future visitors.
Base component definition
import React from 'react'
import styled from 'styled-components'
const ContainerWrapper = styled.div`
width: 100%;
max-width: 1200px;
padding-left: 5%;
padding-right: 5%;
margin-left: auto;
margin-right: auto;
`
export default function Container({ children, ...props }) {
return (
<ContainerWrapper {...props}>
{children}
</ContainerWrapper>
)
}
Extended component definition
Obs.: note that the extended component is an article, while the base component is a div, and so far they have no relationship.
Also note that the base component (Container) has been imported but not yet used.
import React from 'react'
import styled from 'styled-components'
import Container from '../../common/Container'
const HeroWrapper = styled.article`
height: 100vh;
padding-top: 74px;
background-repeat: no-repeat;
background-position: center;
background-size: cover;
background-attachment: fixed;
`
Invoking componentes
Now, in the same file where I declared the extended component, I just call the base component, informing the name of the extended component in the as attribute.
export default function PostsWrapper() {
return (
<Container as={HeroWrapper}>
{/* ... */}
</Container>
)
}

How do you pass an image to a styled component?

I'm using styled-components in ReactJS and I'm trying to create a component that can take in the background-image as a prop. After some research, I've tried this:
import SpeechBubble1 from '../images/home_images/Speech 1.png';
...
const SpeechBubble = styled.div`
background-image: url(${props => props.background});
`;
...
<SpeechBubble background={SpeechBubble1} />
But it doesn't work. Checking in the browser element window, I can see I'm getting an Invalid property value for background-image.
What am I doing wrong?
Edit:
I also tried doing this, which hasn't worked:
<SpeechBubble style={{background: `url(${SpeechBubble1})`}} />
Make sure you are including a height for the styled component, otherwise, it won't display anything (unless it has children that define its dimensions).
Working example:
components/Container
import styled from "styled-components";
const Container = styled.div`
height: 100vh;
background-image: url(${({ background }) => background});
background-repeat: no-repeat;
background-size: cover;
`;
export default Container;
index.js
import React, { Fragment } from "react";
import { render } from "react-dom";
import reactbg from "./images/reactbg.png";
import Container from "./components/Container";
import GlobalStyles from "./components/GlobalStyles";
import Title from "./components/Title";
const App = () => (
<Fragment>
<GlobalStyles />
<Container background={reactbg}>
<Title>Hello World</Title>
</Container>
</Fragment>
);
render(<App />, document.getElementById("root"));
Index.js
import React from 'react'
import {ProfilePic} from './NavigationElements'
import profileimg from '../../images/profileimg.jpg'
const Navigation = () => {
return (
<NavigationWrapper>
<ProfilePic src={profileimg} alt="" />
</NavigationWrapper>
)
}
export default Navigation
NavigationElements.js
import styled from "styled-components";
export const NavigationWrapper = styled.div`
color: #fff;
`
export const ProfilePic = styled.img`
width: 5vh;
height: 3vh;
margin: 55px;
`
You can use inline styling:
<SpeechBubble style={{background: `url(${SpeechBubble1})`}} />

styled-components causing unexpected behaviour when rendering props

I have a WhiteBox react component which simply renders a white box with some styles.
I have a SmallBox react component which simply uses WhiteBox to render a more specific box.
I have a Content react component which renders three SmallBox boxes which does what it's supposed to do (renders three white boxes).
However when I tried to add a text as a props from the parent, the white box is aligned with some unexpected margin from top.
NOTE: when I simply put "This is a text" the css is okay, but when I send "this is a text" as props.text, the whitebox is rendered with extra margin from top.
I Use styled-components and react as I said.
I've tried to console.log the text, and everything seems to be okay. I also tried to switch the props.children or props.text and it does not work
-----------------White Box Component ----------------------
import styled from "styled-components";
const StyledBox = styled.div`
display: inline-block;
width: ${props => props.width}px;
height: ${props => props.height}px;
margin-right: ${props => props.marginRight}px;
margin-left: 100px;
background-color: white;
border-radius: 5px;
font-size: 13px;
font-weight: 700;
text-transform: uppercase;
color: #646777;
padding: 10px;
`;
const WhiteBox = props => {
return (
<StyledBox
width={props.width}
height={props.height}
marginRight={props.marginRight}
>
{props.text} // if I change this to simply "this is a text" it works well. somehow the props.text is causing problems.
</StyledBox>
);
};
export default WhiteBox;```
-----------------Small Box Component ----------------------
import React from "react";
import styled from "styled-components";
import WhiteBox from "../whitebox/white-box";
const SmallBox = props => {
return (
<WhiteBox width={320} height={130} marginRight={70} marginLeft={70} text={props.text}>
</WhiteBox>
);
};
export default SmallBox;
-----------------Content Component ----------------------
import React, { Component } from "react";
import SmallBox from "./smallbox/small-box";
import styled from "styled-components";
const StyledContent = styled.div`
position: absolute;
left: 320px;
top: 80px;
width: 100%;
height: 100%;
background-color: #f1f3f7;
`;
class Content extends Component {
render() {
return (
<>
<StyledContent>
<SmallBox text="this text is great" /> // causing problem
<SmallBox />
<SmallBox />
</StyledContent>
</>
);
}
}
export default Content;
The issue has to do with how many lines are rendered. The longer the text in the props, the more the lines rendered.
One solution would be to change the display property for WhiteBox:
const StyledBox = styled.div`
display: inline-flex;
....
`;
Another solution would be to override the default style vertical-align: baseline, simply add vertical-align: top;
const StyledBox = styled.div`
display: inline-block;
....
vertical-align: top;
`;

Resources