EzDev.org

styled-components

styled-components - Visual primitives for the component age ?? spectrum-logo visual primitives for the component age. use the best bits of es6 and css to style your apps without stress ??


Styled-components organization

I want to use styled-components in my app and I am wondering how to organize it.

Basically styled-components are assigned to specific component for reusability.

But what about styled-components which I would like to use many times in other components (for example animations components)? Should I create a file where I will keep these 'global' styled-components and import it to many components?

Is it good practice?


Source: (StackOverflow)

Target another styled component on hover

What is the best way to handle hovers in styled-components. I have a wrapping element that when hovered will reveal a button.

I could implement some state on the component and toggle a property on hover but was wondering if there is a better way to do this with styled-cmponents.

Something like the following doesn't work but would be ideal:

const Wrapper = styled.div`
  border-radius: 0.25rem;
  overflow: hidden;
  box-shadow: 0 3px 10px -3px rgba(0, 0, 0, 0.25);
  &:not(:last-child) {
    margin-bottom: 2rem;
  }
  &:hover {
    .button {
      display: none;
    }
  }
`

Source: (StackOverflow)

UI libraries using styled components [closed]

I'm guessing not all ui frameworks are easily used together with styled components; since their specificity could be too high etc. Am I correct in this regard? Is there any ui frameworks built with styled components? What are some good frameworks that work really well with styled components while not being written in it?

Br Oskar


Source: (StackOverflow)

Dynamic Theme in Styled Components

I'm using styled-components in my React app and wanting to use a dynamic theme. Some areas it will use my dark theme, some will use the light. Because the styled components have to be declared outside of the component they are used in, how do we pass through a theme dynamically?


Source: (StackOverflow)

How does Animated.Component / createAnimatedComponent(Component) differ from Component?

We are trying to figure out cause of following issue from styled-components project: https://github.com/styled-components/styled-components/issues/389

There were some changes made to refs + setNativeProps that broke animation in one place, assumingly because some animated related information is not being passed down correctly.

Hence the question to understand how createAnimatedComponent alters initial component, whats added? What could cause animation to break if not passed down correctly?

Please provide ideas / detailed answer if you know what could be causing this issue.

UPDATE Breaking change related to the issue occurred somewhere within this file for reference innerRef passes down ref, isTag function checks if it is a native component.


Source: (StackOverflow)

How to get the theme outside styled-components?

I know how to get the theme from components that are created using the styled way:

const StyledView = styled.View`
    color: ${({ theme }) => theme.color};
`;

But how to get from normal components or apply it for different properties? Example:

index.js

<ThemeProvider theme={{ color: 'red' }}>
    <Main />
</ThemeProvider>

main.js

<View>
    <Card aCustomColorProperty={GET COLOR FROM THEME HERE} />
</View>

Notice how the property that needs the theme is not called style


Source: (StackOverflow)

Using Animated with styled-components (react-native)

I'm experiencing an error stating following (tested via iOS):

Cannot read property 'getScrollableNode' of null

While trying to use react-native's Animated along side styled-components styling tool for react and react-native.

Here is example of a <Logo /> component I created:

import React from 'react';
import { Image, Dimensions } from 'react-native';
import styled from 'styled-components/native';

const { width } = Dimensions.get('window');
const logoWidth = width - (width * 0.2);
const logoHeight = logoWidth * 0.4516;

const SLogoImage = styled(Image)`
  width: ${logoWidth};
  height: ${logoHeight};
`;

const Logo = ({ ...rest }) => (
  <SLogoImage
    source={require('../assets/logo.png')}
    {...rest}
  />
);

export default Logo;

I am then importing this component into one of my scenes where I want to apply animation to it:

import React from 'react';
import { View, Animated } from 'react-native';
import Logo from '../components/Logo';

const ALogo = Animated.createAnimatedComponent(Logo);

class HomeScene extends Component {
  state = {
    fadeAnim: new Animated.Value(0)
  }

  componentDidMount() {
    Animated.timing(
      this.state.fadeAnim,
      { toValue: 1 }
    ).start()
  }

  render() {
    <View>
      <ALogo style={{ opacity: this.state.fadeAnim }} />
    </View>

  }
}

export default HomeScene;

And this results in error mentioned above, tried Googling it and wasn't able to find any sort of explanation to what it is. feel free to request further details if necessary.

Related GitHub issue: https://github.com/styled-components/styled-components/issues/341


Source: (StackOverflow)

Passing further arguments with tagged template literals

I'm working with styled-components and generating components using their tagged template literal syntax such as:

const Button = styled.button`
  background-color: papayawhip;
  border-radius: 3px;
  color: palevioletred;
`

In one case I need to call a function that generates a media query based on a breakpoint and passes the tagged template literal of css to be included within.

for example:

media(12)`
   background-color: papayawhip;
`

The media function might look something like this:

const media = mapValues(width => ({ css: (...args) => css`
  @media (min-width: ${width}rem) {
    ${css(...args)}
  }
`}));

Is passing both a value and a tagged template literal possible, or am I going about this the wrong way?


Source: (StackOverflow)

React styled-components fade in/fade out

I am trying to build a React component to handle fading in and fading out. In the following code, if I pass out as a prop to the component, it is disaplayed as hidden before animating out. I'm trying to have it fade in by default, then fade out when I pass in the out prop. Anyone see a solution to this problem?

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

const fadeIn = keyframes`
  from {
    transform: scale(.25);
    opacity: 0;
  }

  to {
    transform: scale(1);
    opacity: 1;
  }
`;

const fadeOut = keyframes`
  from {
    transform: scale(1);
    opacity: 0;
  }

  to {
    transform: scale(.25);
    opacity: 1;
  }
`;

const Fade = styled.div`
  ${props => props.out ?
    `display: none;`
   : `display: inline-block;`
   }
  animation: ${props => props.out ? fadeOut : fadeIn} 1s linear infinite;
`;

function App() {
  return (
    <div>
      <Fade>&lt;💅test&gt;</Fade>
    </div>
  );
}

export default App;

WebpackBin running example


Source: (StackOverflow)

How to work with styled components in my react app?

I had trouble naming this question and it seems quite broad, so, forgive me oh moderators. I'm trying out styled components for the first time and trying to integrate it into my react app. I have the following so far:

import React from 'react';
import styled from 'styled-components';

const Heading = styled.h1`
    background: red;
`;

class Heading extends React.Component {

    render () {

        return (
            <Heading>
                {this.props.title}
            </Heading>
        );
    }

}

export default Heading;

So, just a normal class, but then I import styled components up top, define the const Heading, where I specify that a Heading really is just a styled h1. But I get an error stating that Heading is a duplicate declaration since I also say class Heading....

I'm obviously completely missing something here. All the examples online doesn't actually show how you also use this with React. I.e. where do I define my class, my constructor, set my state, etc.

Do I have to move the styled component into it's own file, i.e.:

import styled from 'styled-components';

const Heading = styled.h1`
    background: red;
`;

export default Heading;

Then create a React component that will serve as a wrapper of sorts, e.g. 'HeadingWrapper':

import React from 'react';
import Heading from './Heading';

class HeadingWrapper extends React.Component {

    render () {

        return (
            <Heading>
                {this.props.title}
            </Heading>
        );
    }

}

export default HeadingWrapper;

A bit of clarity on this would greatly be appreciated! Thanks :)


Source: (StackOverflow)

How can I opt for React Styled-Components to generate a physical CSS file?

I need the CSS that is provided to styled-components to be output to a physical CSS file inside of my public/css directory.

export const MyComp = styled.div`
  width: 100%;
  height: 500px;
`

Along with styles from all other styled-components, the above component would output into public/css/styled.css:

.Components_MyComp__a39t9ag0248f {
  width: 100%;
  height: 500px;
}

I am using:

"webpack": "^2.6.1",
"styled-components": "^2.0.1",

Source: (StackOverflow)

How to achieve tag agnostic styled components?

If I want a button but, only the presentational part of that, so if I do:

import styled from 'styled-components'

const Button = styled.button`
  color: red;
  text-align: center;
`

I'm forced to render a button tag, but what about if semantically I need an anchor?


Source: (StackOverflow)

importing images in React.js with styled-components

I am using styled-components and am trying to set a background image like so

const HeaderImage= styled.div`
    background-image: url('../../assets/image.png');
';

I've also tried without the quotes, like so

const HeaderImage= styled.div`
        background-image: url(../../assets/image.png);
 ';

In both cases, I get the same result

http://localhost:3000/assets/image.png Failed to load resource: the server responded with a status of 404 (Not Found)

I am using Richard Kall's react starter

The file is definitely in the specified location.

Am I loading it incorrectly?

I should mention, I'm very new to this (React, and styled-components)


Source: (StackOverflow)

React Styled Components - How to access raw html

I have a ref on a component I am converting over to a styled component in my app. The ref is used to access the offsetHeight and scrollHeight properties on the raw html element of the component. Once I switched this component to a styled component, the ref now points to the styled component instead of the raw html element, and I'm unsure how to reference the base element. Can this be done?

example:

const TextArea = styled.textarea`
  display: block;
  margin: 0 0 0 18%;
  padding: 4px 6px;
  width: 64%;
  font-size: 1rem;
  color: #111;`;

export default class Input extends Component {
  componentDidMount() {
    const height = this.textInput.scrollHeight;
    // do something....
  }
  render() {
    return (
      <div>
        <TextArea
          ref={(input) => this.textInput = input}
        ></TextArea>
      </div>
    );
  }
}

Source: (StackOverflow)

Defining a function inside a template literal

I'm using styled-components as a solution to styling for React. They've got a nice approach that uses template literals to interpolate CSS. The template literals are passed the component's props so that you can do things like:

const PasswordsMatchMessage = styled.div`
    background: ${props => props.isMatching ? 'green' : 'red'};
`

The result is a component that renders a div tag with either a green or red background depending on the value of isMatching. The above would be used via JSX like this:

<PasswordsMatchMessage isMatching={doPasswordsMatch}>...</PasswordsMatchMessage>

Every time the value of props changes, this string is going to be re-interpolated. Which finally brings me to my question:

Does the arrow function defined inside the template literal get re-defined every time the template literal is interpolated?

If so, then I may consider creating functions outside the template literal and just passing those in, e.g.

const PasswordsMatchMessage = styled.div`
    background: ${isMatchingFn};
`

Source: (StackOverflow)