Search code examples
reactjstypescriptstyled-components

React typescript styled component slider not working in component


I have a demo here

It's a simple react app using typescript and styled components.

I have a slider that changes the height of the red box that.

The red box is a styled component and I pass the height as a prop.

This all worked but stopped working when I surround it all in another styled component to style the page.

The console has lots of warnings like

The component styled.div with the id of "sc-dlnjwi" has been created dynamically.
You may see this warning because you've called styled inside another component.
To resolve this only create new StyledComponents outside of any render method and function component.

Can anyone explain whats happening here an why the slider won't work when inside another styled component


Solution

  • You can't create a styled component inside another component's declaration. This defeats the purpose of styled components. You can't define any component inside another component either. React just isn't built to handle that situation, and wouldn't know how to keep track of the components. If you want to learn more about why this is the case, you could look into the VirtualDOM, and the React node tree and how it is generated. It's a complicated subject, but the gist of it is when you're creating a functional component, that function returns a component tree. If you create components inside other components like you did, they don't get passed through the pipeline they need to go through to get hooked up to everything, and object references get lost.

    Instead, move the styled component out of your app component declaration - either to their own files, or even just somewhere else in that same file - and you won't have any problems.

    I'm assuming you did this because you need to change styling based on the app component's state. You can still do this by passing the state to the styled components as props. There are some examples of this on the styled-components docs:

    https://styled-components.com/docs/basics