Encountering issues initializing JavaScript while utilizing React.JS alongside Materialize version 1.0.0

Struggling to migrate our projects from materialize-css v1.0 to react.js using npm. Has anyone else faced this challenge and found any solutions?

I can easily use the css portion by referencing the npm module in Index.js.

The issue arises when trying to initialize the minified js with individual components. I've provided an example of Index.js for css entry point and the sidebar component where I'm encountering difficulties with initializing the minified js. The configuration in App.js is also included for reference. The goal was to divide the project into separate components, starting with getting the sidebar js initialized first.

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import 'materialize-css/dist/css/materialize.min.css';
import App from './components/App';
ReactDOM.render(<App />, document.getElementById('root'));

App.js

import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
// import Header from './header/Header';
// import Footer from './Footer';
import Landing from './landing/Landing';
import About from './About';
import Projects from './Projects';
class App extends Component {
 render() {
 return (
 <div>
 <BrowserRouter>
 <div>
 {/*<Header />*/}
 <Route exact path="/" component={Landing} />
 <Route exact path="/about" component={About} />
 <Route exact path="/projects" component={Projects} />
 {/*<Footer /> */}
 </div>
 </BrowserRouter>
 </div>
 );
 }
}
export default App;

Landing.js

import React, { Component } from 'react';
import M from 'materialize-css/dist/js/materialize.min.js';
// import { Link } from 'react-router-dom';
import './Landing.css';

class Landing extends Component {
  componentDidMount() {
    console.log(M);
    const sideNav = document.querySelector('.button-collapse');
    console.log(M.Sidenav.init(sideNav, {}));

    M.Sidenav.init(sideNav, {});
  }

  render() {
    return (
      <div className="main-header">
        <div className="primary-overlay">
          <div className="navbar-fixed">
            <nav className="transparent">
              <div className="container">
                <div className="nav-wrapper">
                  <a href="#home" className="brand-logo">
                    TEST
                  </a>
                  <a data-activates="side-nav" className="button-collapse">
                    <i className="material-icons">menu</i>
                  </a>

                  <ul className="right hide-on-med-and-down">
                    <li>
                      <a href="#home">Home</a>
                    </li>
                    <li>
                      <a href="#about">About</a>
                    </li>
                    <li>
                      <a href="#testimonials">Testimonials</a>
                    </li>
                    <li>
                      <a href="#contact">Contact</a>
                    </li>
                    <li>
                      <a className="btn blue">Download</a>
                    </li>
                  </ul>
                </div>
              </div>
            </nav>
          </div>

          {/* Side Nav: fixed navbars must go right underneath main nav bar */}
          <ul id="side-nav" className="side-nav">
            <h4 className="blue-grey darken-4 center">TEST</h4>
            <li>
              <a className="divider" />
            </li>
            <li>
              <a href="#home">Home</a>
            </li>
            <li>
              <a href="#about">About</a>
            </li>
            <li>
              <a href="#testimonials">Testimonials</a>
            </li>
            <li>
              <a href="#contact">Contact</a>
            </li>
          </ul>

          {/*-- Showcase */}
          <div className="showcase container">
            <div className="row">
              <div className="col s12 main-text">
                <h5>You found the...</h5>
                <h1>Right Place To Start</h1>
                <p className="flow-text">
                  To take your business to the next level with our services that
                  have taken companies to the fortune 500
                </p>
                <a href="#about" className="btn btn-large white black-text">
                  Learn More
                </a>
                <a href="#contact" className="white-text">
                  <i className="material-icons medium scroll-icon">
                    arrow_drop_down_circle
                  </i>
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default Landing;

Experiencing some errors with anchor tags and seeing issues in the console. Any tips on resolving this along with the initialization of the sidebar JavaScript would be greatly appreciated.

https://i.sstatic.net/RVeTp.jpg

https://i.sstatic.net/ejQCb.png

If anyone has encountered these challenges before, your assistance would be invaluable...

Cheers!

[![enter image description here][3]][3]

Answer №1

The button trigger code needs to be corrected. You should use data-target and the class should be sidenav-trigger. The side nav must also have the class name sidenav. Using side-nav with a hyphen will not function correctly:

<a href="#" data-target="side-nav" className="sidenav-trigger button-collapse">
    <i className="material-icons">menu</i>
</a>

It's recommended to use refs instead of manually accessing the DOM in react development. Add a ref callback to the sidenav element and utilize it for initialization:

class Landing extends Component {
    onRef = nav => {
        this.nav = nav;
        M.Sidenav.init(nav);
    };

    render() {
        return (
           {/* ... */}

            <ul ref={this.onRef} id="side-nav" className="sidenav">
                <li><a className="divider" /></li>

                {/* ... */}
            </ul>

            {/* ... */}
        );
    }
}

See a functional example with your updated markup:

https://codesandbox.io/s/xllp3wrnvo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble invoking an express route on mobile devices using the .click method

I'm experiencing a strange issue where my code works perfectly in Chrome browser but fails to function on my phone. Here's the snippet of code causing the problem: $('#plusSign').on('click', function() { var myLin ...

When the click event occurs, add a class. After a delay using a timeout function, remove the added

I am currently using Jimdo and I have a section where I can edit all the codes, which is working fine except for one feature. Any assistance would be greatly appreciated! Here is the code that adds a class to an animated SVG image with its status set as d ...

Saving user-generated inputs within a React.js component's state, focusing on securely handling passwords

Curious about forms in React.js? I don't have any issues, but I'm wondering if there are potential flaws in my approach. I've set up a basic form with two inputs for email and password: <input type="email" name="email" value= ...

A guide on accentuating the active menu item using PHP

Looking for a solution in the header.php file. How can I highlight the current page in a menu navigation included on every page of my website using only include("header.php")? Any help is much appreciated. Thank you <div class="form-inline" id="myDIV" ...

Completing a submission on a bootstrap form, using innerHTML and displaying an alert

I am currently having an issue with navigating to the home page after submitting a form in Bootstrap. Although I have successfully implemented an alert message upon submission, the page does not redirect to the home page as expected. Instead, it redirects ...

Getting the value of a JSON object in CodeIgniter can be easily achieved by using the appropriate

My current project involves using the codeigniter framework to build a website. I am making an AJAX request with jQuery to retrieve data from the server. I have experimented with two different methods of receiving the data: one in a PHP associative array a ...

Configuring AWS: Directing subdomains to distinct Elastic Beanstalk environments

My setup on Amazon AWS includes two Elastic Beanstalk environments - one for hosting my React client and another for hosting a Node.js API used by the client. I own the domain some-domain-name.com, and now I want to create two sub-domains: app.some-doma ...

The fetch method in Express.js resulted in an error 404 because the requested URL could not be found

Having trouble locating the URL when trying to fetch data for a POST request. I want to mention that my code is written in node.js and express.js. The error message being generated: const form = document.querySelector('form'); form.addEventList ...

Guide to making a Material Design Radial effect animation

I am looking to create a unique toolbar effect by following the material design radial reaction choreography guideline. https://i.stack.imgur.com/6oB8r.gif I want to achieve this using an angular 2 transition, but I need some guidance on how to implement ...

problem with transmitting information through $.ajax

I'm facing a frustrating issue with the $.ajax()... function in my PHP code. I am unable to retrieve the data sent by the ajax request. <?php if ($_POST){ include 'Bdd_connexion.php'; $filiere = $_POST['filiere']; ...

html5-jquery checkbox change event not firing

I successfully implemented an on/off switch using the method outlined in for HTML5. The functionality of the switch itself is working perfectly - click on it to toggle between states and query the checked state of the input/checkbox. However, I am facing ...

What is the best way to combine multiple classes when declaring them in CSS?

I'm attempting to combine the following code snippets (possibly misunderstood the term) - is there a way to have them both perform the same function without creating another class with identical attributes? .games span { display: inline-block; ...

Stack div on top of div

It seems like I'm facing a simple problem that needs a solution. I have two container divs .topwrap{ position:relative; top:100px; background:#00C; } </i> and .lowerwrap{ position:relative; ...

Execute a function on a canvas timer using the setTimeout method

I'm having an issue with my setTimeout function in this code. I want it to call a timer function for a delay, but it's not working consistently every second. Why is that happening? <head> <script> function timer(sec) { var c = do ...

Converting a string into a list extracted from a text document

Within a file, the data (list) is structured as follows: [5,[5,[5,100,-200],200,-400],300,-500] Upon reading this file in an angular application, the contents are converted into a string object like so: "[5,[5,[5,100,-200],200,-400],300,-500]" Is there ...

Mocking a third-party callback function in Jest for method implementation

Utilizing Nest + Cognito for user authentication in an application, I have a method within my Authentication service that requires testing/mocking: async cognitoRegister(userPool: CognitoUserPool, { name, password, email }: AuthRegisterInput): ...

Beware of overwriting the first element in an array when creating it with a while loop in JavaScript or AppsScript

I am attempting to generate an array containing all dates within a specified time frame. To test this, I have chosen Feb 9 - Feb 13 as the date range. Ideally, the resulting array should display [Feb 9, Feb 10, Feb 11, Feb 12, Feb 13]. Upon revisiting an o ...

Zooming does not activate the onZoom event

I have created a line chart using react-chartjs-2 and incorporated the chartjs-plugin-zoom plugin. My goal is to have the zoom level displayed in the console whenever the chart is zoomed in or out. However, it seems that the onZoom function is not being tr ...

Utilizing HTML5 canvas to extract pixel data from an image loaded from an external source

When it comes to security reasons, doing it directly may not be feasible. Nevertheless, there are rumors circulating about certain image-hosting platforms that permit the use of their images in a comparable way (could Google Picasa be one?). I might be mis ...

Reached the maximum call stack size while trying to include a footer in my Jade template

Hey there, it's a bit odd but here's the scenario. I've been experimenting with Express and the Jade templating system. I have a pretty simple layout.jade file: doctype 5 html head title= title link(rel='stylesheet', h ...