Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Document.ready functions with ReactJS

Tags:

I'm kinda new to ReactJS, learning and making one project. And i got stuck with such an issue.
I have app with authorization. User enters credentials and proceeds to app. There is a navigation menu made using external libraries. It slides up and down and initializes with something like

$(document).ready(function(){
  $('.menu-class').makeCoolMenu();
}); 

But, when user is not signed in - app not showing menu. This code runs and does nothing. After authorization menu appears, but of course not working.
I googled it, but found nothing about it. Just something about "dont use jquery with React". But what is the correct way to do such thing? Seems like i cant run

$('.menu-class').makeCoolMenu();

from within the application.

Thanks in advance.

like image 858
ikebastuz Avatar asked Jun 25 '18 11:06

ikebastuz


People also ask

How do I use document ready in react?

ready() to call jquery function in react . You can make use of componentDidMount() just as your $(document). ready() to ensure that DOM is rendered. Then access jQuery dependent libraries as local variables to apply for DOM elemnets.

What is difference between componentDidMount and useEffect?

From the previous question, we found out that componentDidMount doesn't have the same behavior with useEffect hook, because componentDidMount invoked synchronously before the browser paints the screen, while useEffect is invoked asynchronously after the browser has already painted the screen.

What is document ready function?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.

Why document ready is deprecated?

In jQuery 3.0, all other syntax methods except $(handler); are deprecated. The official justification is: This is because the selection has no bearing on the behavior of the . ready() method, which is inefficient and can lead to incorrect assumptions about the method's behavior.


2 Answers

Generally jquery is not needed in React app if you use it properly.

There are life hooks for React component that you can use to initialize something when content is loaded: https://www.fullstackreact.com/30-days-of-react/day-7/

Life hook that you need it ComponentDidMount that is fired when component is rendered first time.

like image 162
Mario Petrovic Avatar answered Sep 28 '22 19:09

Mario Petrovic


I think your problem is how to integrate with other libraries like jQuery. You can follow this docs https://reactjs.org/docs/integrating-with-other-libraries.html

like image 35
Rizal Ibnu Avatar answered Sep 28 '22 18:09

Rizal Ibnu