Search code examples
javascripthtmlcssreactjsparallax

react-scroll-parallax <ParallaxProvider/> to a div


I am trying to make react-scroll-parallax work on a div using this module: https://www.npmjs.com/package/react-scroll-parallax

I am trying to set up the parallax provider to not just point to the body but to a specific div. I am trying to ref the element (which is the scrollContainer).

The challenge is that I am using a "scrolling div" between the footer and the header, so doing the parallax on the would not work.

I tried to create a ref and reference it on the without success.

The documentation says to ref an element as an option to ScrollContainer: scrollContainer Element: Optionally set the container that has overflow and will contain parallax elements. Defaults to the HTML body

 constructor(props) {
    super(props);
    this.myScrollDiv = React.createRef();
  }

/////////////////



<ParallaxProvider scrollContainer={this.myScrollDiv.current}>
     <div className="page-scroller site-wrapper pb-5" ref={this.myScrollDiv}>
               ///Content
     </div>
</ParallaxProvider>

I would love for the .page-scroller div to handle parallax.

Solution

  • Disclaimer: I've never used react-scroll-parallax library. The answer is base-off on the source code.

    Welcome to Stack Overflow, @stephanesng 👋

    As I looked into the source code, I found a Storybook code snippet.

    It looks like you need to pass the ref variable itself, not ref.current.

    export default class ScrollContainer extends React.Component {
        static defaultProps = {
            scrollAxis: 'vertical',
        };
    
        constructor() {
            super();
            this.state = {
                scrollContainer: null,
            };
            this.scrollContainer = React.createRef();
        }
    
        componentDidMount() {
            this.setState({ scrollContainer: this.scrollContainer.current });
        }
    
        render() {
            return (
                // ............ You pass the `ref` not `ref.current` 👇                       
                <div className="scroll-container" ref={this.scrollContainer}>
                    <ParallaxProvider
                        scrollContainer={this.state.scrollContainer}
                        scrollAxis={this.props.scrollAxis}
                    >
                        {this.props.children}
                    </ParallaxProvider>
                </div>
            );
        }
    }
    

    So that means, you'd need to pass this.myScrollDiv, not this.myScrollDiv.current to scrollContainer prop.

    And also, your ref needs to be outside of the ParallaxProvider.

    <div className="page-scroller site-wrapper pb-5" ref={this.myScrollDiv}>
        <ParallaxProvider scrollContainer={this.myScrollDiv}>
                   ///Content
        </ParallaxProvider>
    </div>
    

    If I am wrong, I will delete the answer.