Adam White
Adam White

Reputation: 1136

Using scripts in React without bundling

I'm trying to use Rellax, a JS parallax library, in my React app.

I've downloaded Rellax through npm and imported Rellax into a React component. Rellax's docs then require assigning a rellax variable to the new Rellax constructor, which takes as an argument the query selector.

Like so:

var rellax = new Rellax('.rellax'); 

However, when I call the component, I receive this error:

Error: The elements you're trying to select don't exist.

However, I do use this class in the component itself.

Below is the full component:

import React from 'react';
import Rellax from 'rellax';
import 'sample.css';

var rellax = new Rellax('.rellax');

const SampleComponent = () => {

  return (<div>
        <div className="rellax square"></div>
        <div className="rellax rectangle"></div>
      </div>);
}

export default SampleComponent;

Does anyone have any idea why this isn't working?

Below is a link to Rellax docs: https://github.com/dixonandmoe/rellax

Thanks!

Upvotes: 2

Views: 554

Answers (1)

Sidney
Sidney

Reputation: 4775

That new Rellax('.relax') constructor is called as soon as that file is loaded (ie, imported by another component). But when the file is loaded, obviously the component hasn't been rendered yet, so the .rellax elements aren't in the DOM.

Instead, you need to call the Rellax constructor when you know the component has rendered. That's what React's componentDidMount is used for. It gets called when the component has been rendered in the DOM (so libraries that use DOM elements can find the element they need).

import React from 'react';
import Rellax from 'rellax';
import 'sample.css';

class SampleComponent extends React.Component {
  componentDidMount() {
    // We can keep a reference to Rellax in case we need it later
    this.rellax = new Rellax('.rellax')
  }

  render() {
    return (
      <div>
        <div className="rellax square"></div>
        <div className="rellax rectangle"></div>
      </div>
    )
  }
}

export default SampleComponent

Upvotes: 5

Related Questions