Search code examples
javascriptjqueryreactjsmaterialize

React - how to add jquery script with Materialize's function


Hello I'd like to add jquery to a react app, but I don't know how to do it. I use materialize to build a navbar and I want to use .sidenav function from their lib.

I installed jquery

npm install jquery

and add

import $ from "jquery";

to ./app.js, then in Navbar.js i got /

import { Link } from "react-router-dom";

const Navbar = () => {

  return (
    <>
      <nav className="nav-wraper">
        <div className="container">
          <a Link to="/" className="brand-logo">
            Blog
          </a>
          <a Link to="/" className="sidenav-trigger" data-target="mobile-links">
            <i className="material-icons">menu</i>
          </a>
          <ul className="right hide-on-med-and-down">
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/create">New Blog</Link>
            </li>
            <li>
              <Link to="/signup">Sign up</Link>
            </li>
          </ul>
        </div>
      </nav>

      <ul className="sidenav" id="mobile-links">
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/create">New Blog</Link>
        </li>
        <li>
          <Link to="/signup">Sign up</Link>
        </li>
      </ul>
    </>
  );
};

export default Navbar;

Where am I supposed to put this code?:

$(document).ready(function () {
        $(".sidenav").sidenav();
      });

Solution

  • In a way, you don't need to use $(document).ready statement. instead of that, you can use useEffect with an empty deps array ([]) in functional components or componentDidMount in class components. see the below example: (Remember to use Materilized-css CDNs in index.html). In functional component (As you are):

    import React, { useEffect, useRef } from "react";
    import { Link } from "react-router-dom";
    import M from 'materialize-css';
        
    const Navbar = () => {
        const myNavbar = useRef('');
        useEffect(() => {
            M.Sidenav.init(myNavbar);
        }, []);
    
        return (
            <>
                <nav className="nav-wraper" ref={myNavbar}>...</ul>
            </>
        );
    };
    export default Navbar;
    

    For more information about useEffect and useRef statements, i would like to refer you to the official documentation