0

How does one declare styled components outside of a React component's render() method when using React class syntax?

My motivation is stateful components being accidentally remounted. They are remounted due to their parents being styled components and declared in the render() method. This causes the parents to be recreated every render, and thus their children's state reseting. This topic is discussed on the styled-components FAQ.

2
  • 2
    How is that different to the example provided in the docs you linked? Just declare them outside of your class component and render them as usual. Commented Feb 3, 2019 at 23:13
  • 1
    You can declare them outside of the component and they'll be global. Or in-line. Commented Feb 3, 2019 at 23:13

1 Answer 1

1

What we do is create styled component outside render and then user it:

example.jsx // statefull component

const StyledDiv = styled.div `
   .... styles
`;

class Header extends Component {
 render() {
  return (
    ... use StyledDiv here
   );
  };
 } ;
Sign up to request clarification or add additional context in comments.

2 Comments

I had not thought of declaring the component completely outside of the parent component's class. I thought all child components needed to be defined inside the parent component for React to correctly determine how to update the DOM.
one more pattern I have seen where you can put all these styles components in single file src/components/Styled/example.jsx. Now export and use it in different components. This is good when application grows and re usability is required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.