javascriptcssreactjsstyled-componentsnew-window

Styled-components dynamic CSS is not generated in a new window


I'm using react-new-window to open a popup. The popup includes a few dynamic components (a toggle, a dropdown, etc) styled with styled-components.

Everything is displayed properly until I try to interact with one of the dynamic components and it changes state (say I switch a toggle from off to on). Then it turns out that the CSS class for the new component state, that is normally generated and attached to the <head>, actually gets attached to the <head> of the parent window, not the popup. So my component appears to lose styling.

I have the same bunch of components in the parent window as well. So if I interact with them before opening the popup, the styles get attached to the <head> as usual, and then get copied to the popup and all looks good.

So I see two possible ways I could solve it:

  1. I could tell styled-component to somehow talk to the new window, not the parent.
  2. As a workaround I could somehow programmatically pre-generate all the styles (there isn't a lot of them).

The problem is I'm not sure how to do either of those two things. Any ideas welcome!


Solution

  • Option 1 solution is actually possible through styled-component API:

    import React from 'react';
    import styled, {StyleSheetManager} from 'styled-components';
    import NewWindow from 'react-new-window';
    
    class Parent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          showPopout: false,
        };
        this.nwRef = React.createRef();
      }
    
      render () {
        ... some stuff
        this.state.showPopout && (
        <StyleSheetManager target={this.nwRef.current}>
          <NewWindow
            title="Title"
            features={{width: '960px', height: '600px'}}
            onUnload={() => this.setState({showPopout: false})}
          >
            <div ref={this.nwRef}>
              <Popout isPopout={true}>
                ... popup stuff
              </Popout>
            </div>
          </NewWindow>
        </StyleSheetManager>
      )}
    }