Search code examples
reactjsreact-navigationmetronic

Problem in converting static website template to react project


I am new to reactjs. First, I will summarize what happened to me. When I tried to move to another page using useNavigate() in react-router-dom, some click events not fired in that page. But when refresh that page, javascript works well. I want to make react website(just look like medium.com) using metronic static website template. So I added required css and js files in index.html file in public folder like below.

    ...
    <link href="%PUBLIC_URL%/assets/plugins/global/plugins.bundle.css" rel="stylesheet" type="text/css" />
    <link href="%PUBLIC_URL%/assets/css/style.bundle.css" rel="stylesheet" type="text/css" />
    <title>React App</title>
   </head>
   <body>
    <div id="root"></div>
   </body>  
  <script src="%PUBLIC_URL%/assets/plugins/global/plugins.bundle.js"></script>
  <script src="%PUBLIC_URL%/assets/js/scripts.bundle.js"></script>
  <script src="%PUBLIC_URL%/assets/plugins/custom/fullcalendar/fullcalendar.bundle.js"></script>
  <script src="%PUBLIC_URL%/assets/js/custom/widgets.js"></script>
  <script src="%PUBLIC_URL%/assets/js/custom/apps/chat/chat.js"></script>
  <script src="%PUBLIC_URL%/assets/js/custom/modals/create-app.js"></script>
  <script src="%PUBLIC_URL%/assets/js/custom/modals/upgrade-plan.js"></script>

And I made a login and dashboard page. After successfully logged in, then page navigates to dashboard page. (I omitted unnecessary codes for simplicity.)

...
import { useNavigate } from "react-router-dom";
...
const Login =() => {
 const navigate=UseNavigate();
 useEffect(() => {
  dispatch(login(credential))
  .unwrap()
  .then(()=>{
    navigate("/dashboard")});

But in dashboard page, original javascript came from Metronic does not work. If I refresh page, then javascript works well. ( dropdown event when click button) plugins.bundle.js and scripts.bundle.js are responsible for click event handling and they are already included in page. Maybe my method for using Metronic template in react is incorrect. Please solve this problem. I tried all day long, but could not find solution. Thanks in advance.


Solution

  • Finally I solved this problem. For those who would confront this problem, I will explain the root cause and solution! All Metronic bootstrap menu components are initialized automatically, but sometimes like me should initialize instances. In my problem, I could not fire dropdown menu event because when navigating to dashboard(re-rendering), not initialized automatically. So, in useEffect hook, just initialize KTMenu like below.

    KTMenu.createInstances();
    

    For those similar cases, check this manual metronic documentation how to initialize instances, then add initialization code in useEffect hook.