Home > Blockchain >  How to Migrate JQuery Code to React for Dark Mode Toggle
How to Migrate JQuery Code to React for Dark Mode Toggle

Time:09-10

I found this simple website that has code I was able to adapt for my personal website, but I don't know how to implement the javascript.

Site: https://codepen.io/sashatran/pen/rPaLgG Personal Website: aaronwoods.info

This is the code I'm trying to put in my App.js using React.

$(".theme-switch").on("click", () => {
  $("body").toggleClass("light-theme");
});

I am very confused. I know what the JQuery is saying too. I just don't know how to write it. I am new to Reactjs and really am adapting this template I found. I would appreciate any help with re-writing this.

This is the start of my App.js.

import "./sass/main.scss";
import moment from "moment";
import { useState } from "react";

const tag_color = {
  Code: "#386FA4",
  Paper: "#DE7254",
  Misc: "#67a286",
};

function BackToTheTop() {
  return (
    <li className="back-to-the-top hidden" id="back-to-the-top">
      <a href="#header" />
    </li>
  );
}

function NavBar({ items }) {
  let links = Object.keys(items)
    .reverse()
    .map((key, i) => (
      <li key={i} className="navbar__item">
        <a href={items[key]}>{key}</a>
      </li>
    ));

  return (
    <ul className="navbar">

CodePudding user response:

We can use jQuery in ReactJs. Here I will tell how we can use it using npm.

  • Step 1: install jQuery package using npm install jquery --save

  • Step 2: now, import $ from jquery into your jsx file where you need to use.

Example:

import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';


//   react code here


$(".theme-switch").on("click", () => {
  $("body").toggleClass("light-theme");
});

// react code here
  • Related