Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I want to use a javascript library like AOS in React, HOW?

I want to use the JavaScript library AOS (https://michalsnik.github.io/aos/) inside of my React application. How do I include it in my App.js file?

import React from 'react';
import logo from './logo.svg';
import './App.css';
import 'aos';

function App() {

  AOS.init();

  return (
    <div className="App">
      <header className="App-header">
        <img data-aos={"fade-left"} src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

AOS needs to be initialized, so I feel like I need to do something like I did in the above code, but it is throwing an error:

Failed to compile ./src/App.js Line 8:3: 'AOS' is not defined no-undef

How would I accomplish this in react?

like image 429
Keith Becker Avatar asked Dec 28 '19 03:12

Keith Becker


3 Answers

With functional components and hooks (useEffect) I did like this:

import React, { useEffect } from "react";
import AOS from "aos";
import "aos/dist/aos.css";

function App() {
  useEffect(() => {
    AOS.init();
    AOS.refresh();
  }, []);

  return (
    // your components
  );
}

export default App;
like image 98
Gabor Szabo Avatar answered Nov 09 '22 11:11

Gabor Szabo


According to the documentation, You will need to call AOS.init() to initialise it within your component. This can be done within your componentDidMount lifecycle hook.

In addition, you should import it by referencing the defaultExport by doing this import AOS from 'aos';

If you are using class components, this is how your code should look like.

import AOS from 'aos';

componentDidMount() {
  // or simply just AOS.init();
  AOS.init({
    // initialise with other settings
    duration : 2000
  });
}

On the other hand, for functional components,

useEffect(() => {
  AOS.init({
    duration : 2000
  });
}, []);

Do remember to add an empty array as the dependency array such that the useEffect hook will only run once when the component is mounted,

like image 42
wentjun Avatar answered Nov 09 '22 12:11

wentjun


Do not forget to import 'aos/dist/aos.css'; I did that mistake waste heavy time .

like image 5
subhajit das Avatar answered Nov 09 '22 11:11

subhajit das