Overriding react components styles with styled component
Asked Answered
A

3

10

I tried to override style of component created by standard way of styled-components(styled.) and both the ways(styled() and style.extends) worked for me.

But when I am trying to override style of simple react component with styled() approach, its rendering the component but not overriding it's style.

Below is snippet of code

import React, { Component } from "react";
import styled from "styled-components";

export default class MyLabel extends Component {
  render() {
    return <label>{this.props.children}</label>;
  }
}

const StyledMyLabel = styled(MyLabel)`
    color: green;
`;

And for display purpose I am using following syntax

<StyledMyLabel>My Styled Label</StyledMyLabel>

Please refer the link on codesandbox which might be useful

Asterism answered 16/8, 2018 at 7:37 Comment(0)
F
11

You have to pass className to desirable styling element manually to make it works.

import React, { Component } from "react";
import styled from "styled-components";

export default class MyLabel extends Component {
  render() {
    return <label className={this.props.className}>{this.props.children}</label>;
  }
}

const StyledMyLabel = styled(MyLabel)`
    color: green;
`;

NOTE:

Consider carefully whether to wrap your own components in a styled component, when it isn't necessary. You will disable the automatic whitelisting of props, and reverse the recommended order of styled components and structural components.

See more info here.

Fluky answered 16/8, 2018 at 7:52 Comment(1)
Updating the link...this one goes to some related info: styled-components.com/docs/…Obstructionist
V
0
<label style={{color: "green"}}>{this.props.children}</label>

or

const style = {color : "green"};
<label style={style}>{this.props.children}</label>
Vilhelmina answered 16/8, 2018 at 7:39 Comment(2)
Can someone explain why this is not the correct answer?Drubbing
@YigitAlparslan people tend to use styled-component not to use inline-style to keep components clean, so the answer is not relevant.Soliz
M
0

There is a much easier way to accomplish this when you want to override a component with pre-existing styles.

Each Component in react comes with a theme property.

//the component you are trying to change the style of
import { AppBar } from 'react-toolbox/lib/app_bar';

//your stylesheet for the new component
import newTheme from './NewAppBar.css'

//inject your new stylesheet for the existing component
<AppBar {...props} theme={newTheme} />
Melancholy answered 20/10, 2023 at 0:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.