Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

styled-components: Styling components without wrapping them in containers/wrappers?

Is it possible to style a react component without having to create a container?

Here's an example of my current problem. I always need to wrap the component in a container/wrapper. Like so ...

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

const PitchSliderContainer = styled.input`
    text-align: right;
    float: right;
`;

const PitchSlider = () => <PitchSliderContainer
    type="range"
    min="0.9"
    max="1.1"
    step="any"
    onChange={this.props.onChange}
/>

export default PitchSlider;

Is there any way to style the PitchSlider without having to create a container?

like image 688
DeveloperJames Avatar asked Oct 18 '25 15:10

DeveloperJames


1 Answers

I think what you have done is the right way. Because that's the whole point of Styled Components. To create reusable presentational components. Here, your PitchSliderContainer is one such styled input component. You could write a more general component that accepts certain props, and renders an <input> based on the props. Such a styled component should definitely have a name too.

What you're asking for could be done in another way. This is not recommended for structural components, but since your component has a single <input> tag, this should be okay:

const PitchSlider = ({ className }) => <PitchSliderContainer
    type="range"
    min="0.9"
    max="1.1"
    step="any"
    onChange={this.props.onChange}
    className={className}
/>

export default styled(PitchSlider)`
  text-align: right;
  float: right;
`;

Make sure you receive className as props and pass it down to your component.

EDIT: As Phil Pluckthun suggested, you could also do this:

const PitchSlider = styled.input.attrs({
  type: 'range',
  min: '0.9'
  max: '1.1'
  step: 'any'
  onChange: this.props.onChange
})`
  text-align: right;
  float: right;
`;
like image 196
Dane Avatar answered Oct 21 '25 05:10

Dane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!