Add styling to child element using Styled Components? - reactjs

Say I want to create a styled component called <NoPrint /> that adds the following CSS to any element passed as child:
#media print
{
display: none !important;
}
How can I do that?
I want to be able to write a styled component like this:
<NoPrint><p>Some paragraph</p></NoPrint>
<NoPrint><Some>Some React component</Some></NoPrint>
I know that I can write:
const NoPrint = styled.div`
#media print
{
display: none !important;
}
`
render(
<NoPrint>
<Something />
</NoPrint>
)
But this component creates a wrapping div, which I do not want.

This is because you have to pass in the component you want to style, IE:
Style a component without wrapper
const NoPrint = styled(myComponent)`
#media print
{
display: none !important;
}
`
this will apply a custom style directly to an element without a wrapper.
Polymorphic prop
Another way is to use a "as" polymorphic prop
const Component = styled.div`
#media print
{
display: none !important;
}
`;
render(
<Component
as="button"
onClick={() => alert('It works!')}
>
Hello World!
</Component>
)

The only way I can see to figure something without having a div would be to have your media query in a css stylesheet with a classname, and pass that classname to your elements.
something like
#media print
.noPrint{
display: none !important;
}
<p class="noPrint" >Some paragraph</p>
To make an element without a div, there is React.Fragment available, but you can't style those...
I don't know if

Realistically you cant escape the wrapping div. You will have to either wrap it somewhere or, create a static styled component that can be included inside other styled components by referencing it.
Example
You can put this in like a style helper file
export const NoPrint = styled.div`
#media print
{
display: none !important;
}
then you can include it in other styled components. But it will not be wrappable around other components without an associated element like a span or div.

Related

styled-components with custom React components: passing props

I have a custom component that takes in a property icon and sets the button's inner image to the corresponding icon as follows:
<custom-button-icon ref={showIcon} slot="right" icon="tier1:visibility-show" onClick={() => isPasswordVisible(false)} />
I would like to apply custom styling to a couple of instances of this component using styled-components. How can I pass the icon prop in so that it still functions (gets passed in as a pop of custom-button-icon)? This is what I have so far but it returns an empty button (with no icon):
export const d2lButtonIcon = ({ icon }) => {
const buttonIcon = styled(`d2l-button-icon`)`
display: flex;
align-items: center;
justify-content: center;
padding: 100px;
margin: 1px;
`
return <buttonIcon icon={icon} />
}
Thanks!
This is a really unusually case because this d2l-button-icon that you are dealing with a custom HTML element rather than a React component.
styled-components can style any React component and any built-in DOM element (a, div, etc.), but I don't think it knows how to deal with a custom DOM element because that's just not the way that we build things in React.
At first I tried passing the style to the d2l-button-icon element, and I got the icon prop to pass through but the style was ignored.
The way that I got this to work is to apply the styles to a div around the element and pass the other props to the d2l-button-icon element itself.
// function component adds styles around the icon button
const UnstyledD2L = ({ className, ...props }) => {
return (
<div className={className}>
<d2l-button-icon {...props} />
</div>
);
};
// can use styled-component to style this wrapper component
const StyledButtonIcon = styled(UnstyledD2L)`
display: flex;
align-items: center;
justify-content: center;
padding: 100px;
margin: 1px;
`;
// example usage with props
export default () => <StyledButtonIcon text="My Button" icon="tier1:gear" />;
However if you aren't super attached to this Brightspace package, I would recommend switching to a UI library that is designed for React.

How to override third party default styles using Styled Components

I'm currently using VideoPlayer from react-video-js-player and I'm trying to override the default height/width styles to have the video inherit the parents height/width.
Since VideoPlayer is simply React wrapper for VideoJS. I assume the styles and class names are the same.
I tried doing something like this:
import VideoPlayer from "react-video-js-player"
export const VideoJS = styled(VideoPlayer)`
position: relative;
height: 100%;
`
Setting the height and width to be 100% in the props doesn't work
<VideoPlayer
controls="true"
height={"100%}
width={"100%"}
src="examplevideo"
/>
.
the parent container is set to 100% width and height.
Any ideas?
I would do something like this , first inspect the video player element in browser to know what is its wrapper, let's say its a div . you can do something like this :
export const VideoPlayerWrapper= styled.div`
>div{
//this will target the videoPlayerwrapper
position: relative;
height: 100%;
}
`

Question about mixing styled-components with material-ui

Hello I am a react newbie and new to styling as well :)
I am trying to style the material-ui Button component with styled components
I am doing this by overriding global class names, I know material-ui introduced global class names like MuiButton-root etc
I am not clear on the use of "&" in parent selector, for example:
const StyledButton = styled(Button)`
&.MuiButton-root {
width: 500px;
}
.MuiButton-label {
color: ${props => props.labelColor};
justify-content: center;
}
`;
The above code works and can achieve the following:
The Button has a width of 500px
The label has a color of red (labelColor is passed in as a prop)
Please see sandbox below for full code
Question:
Why do I need "&" selector for the MuiButton-root, whereas for the MuiButton-label I don't?
Also is this the best way to style material-ui with styled components?
Please see the following sandbox: https://codesandbox.io/embed/practical-field-sfxcu
The '&' selector is used to target the classes and neighbouring elements/classes. Take a look at cssinjs. Its the underlying system behind MUI's styling.
But in short to answer your question;
const StyledButton = styled(Button)`
&.MuiButton-root { //this targets any class that is added to the main component [1]
width: 500px;
}
.MuiButton-label { //in css-in-js this is effectively '& .MuiButton-label [2]
color: ${props => props.labelColor};
justify-content: center;
}
[1] Targets main classes on component
<StyledButton className='test bob'> << this element is targeted
</StyledButton>
[2] Targets child elements either through class or element type. Note the space between & and the actual class.
<StyledButton className='test bob'>
<span className='MuiButton-label'>test</span> << this element is targeted instead
</StyledButton>
You can also use the element tag directly
span {
color: ${props => props.labelColor};
justify-content: center;
}

Styles are not working in through styled components

I am trying to add background-color through styled component.
If add the styles through style={} attribute it is working as expected but If I add the same style in my styled component file it is not working.
//this is working
<MyStyle style={{backgroundColor: '#fff' }}>
//some component here
</MyStyle>
//This is not working.
export const MyStyle = styled.div`
background-color: ‘#fff’;
`;
Can somebody point me here what I am missing here?
The first example is simply using the react style builtin, you don't need styled components to do this.
The code in the second example, you need to remove the quotes around the color, like this:
//This is not working.
export const MyStyle = styled.div`
background-color: #fff;
`;
Styled components takes css syntax, which unlike json syntax, does not have quotes around option names, color names, etc.
You don't have to put single quote around #fff
export const MyStyle = styled.div`
background-color: #fff;
`;
EDITED:
If there are overriding CSS styles that make your div's background not white just yet, and you can't find them, just add !important to this style
export const MyStyle = styled.div`
background-color: #fff !important;
`;
Regarding the issue about finding existing CSS styles that might be overriding your preferred style, take a look at this: https://www.styled-components.com/docs/advanced#existing-css

Styled components for colored tags

Styled components looks great, but I am having trouble organizing my components. My first venture with is a tag list, that automatically colors the tags. After some trial I came up with a component that can be used like this:
// An array of tags. The string hashes determine the color
<ColorTags tags={post.frontmatter.tags} inline/>
It is implemented as follows:
components/
ColorTags // functional component
ColorTagLI // styled component
ColorTagUL // styled component
With:
// ColorTags
import ColorTagLI from './ColorTagLI'
import ColorTagUL from './ColorTagUL'
export default ({tags, inline}) =>
<ColorTagUL>
{tags.map( tag =>
<ColorTagLI key={tag} colorString={tag} inline>
<Link to="/">
{tag}
</Link>
</ColorTagLI>
)}
</ColorTagUL>
// ColorTagUL
export default styled.ul`
list-style-type: none;
margin: 0;
padding: 0;
`
// ColorTagLI
const colorHash = new ColorHash({lightness: [0.4, 0.5, 0.6]});
const hslColor = cString => {
const [h, s, l] = colorHash.hsl(cString)
return `hsl(${h}, ${s*100}%, ${l*100}%)`
}
export default styled.li`
color: white;
background-color: ${props => hslColor(props.colorString)};
display: ${props => props.inline ? 'inline-block' : 'block'};
padding: 0.25rem 0.5rem;
margin: 0.25rem;
> a { text-decoration: none; color: white; }
`
Some questions I have:
What's a good way to discern between styled and regular components? I
decided on appending the HTML tag to the styled components, since
they are always tied to that.
Is it not a problem to have the Link tag inside a Styled component?
Should the ColorTag components be in a folder of themselves? Because they are tightly coupled.
Is using theinline prop a smart way to switch between configurations? It may
result in a lot of conditional statements for margins, padding and
media queries... Perhaps better make two different components?
You can use utility function isStyledComponent.
Why would it be a problem to have a Link component inside styled component?
Matter of opinion, if you believe they are tightly coupled you can create /ColorTag directory with index.js file that exports only what should be exposed.
Yes it may result in a lot of conditional statements, that's why you can extend styles on styled components.
I hope I understood you right and my answers are clear.

Resources