Abhinav
Abhinav

Reputation: 31

How to load an execute a jquery file using react?

I can't tell where the error is and it is not showing alert box onclick on button in jquery There are two files

INDEX.js

import React from "react";
import ReactDOM from "react-dom";
import $ from '../node_modules/jquery'; 
import UsingJquery from './UsingJquery';

ReactDOM.render(   
                <>
                  <UsingJquery/>   
                </>,
                document.getElementById("root") 
);

UsingJquery.jsx

import React from "react";
import $ from 'jquery';


const UsingJquery = () => {
    $('button').on('click',function (){ 
        alert('clicked')
    });

    return(
        <>
            <p>Hi</p>
            <button>Click me</button>
        </>
    )
}

export default UsingJquery;

Upvotes: 1

Views: 3699

Answers (1)

Quentin
Quentin

Reputation: 944116

You are searching the DOM for the element before the component has created the element, returned it, and had it inserted into the DOM.

If you need to access rendered elements then you should use a useRef hook.

import React, {useRef, useEffect} from "react";
import "./styles.css";
import $ from "jquery";

export default function App() {
  const buttonRef = useRef(null);

  useEffect( () => {
    if (!buttonRef.current) return;
    $(buttonRef.current).on("click", function() { 
      alert('clicked'); 
    });
  }, [buttonRef]);

  return (
    <>
      <p>Hi</p>
      <button ref={buttonRef}>Click me</button>
    </>
  );
}

However, you should almost always avoid direct DOM access and use JSX in combination with state and props instead.

const click = () => {
    alert('clicked');
};

const NotUsingJquery = () => {
    return(
        <>
            <p>Hi</p>
            <button onClick={click}>Click me</button>
        </>
    )
}

Upvotes: 2

Related Questions