Update the CSS module in React dynamically

I have a canvas within my Component

When the cursor enters the Canvas, I want it to change to the crosshair style.

import styles from '../css/basic-styles.module.css';

const ImagePreview = () =>{
    [mode,setMode] = useState(0);
    changeMode(mode){
       setMode(mode);
    }
    return (){
        <canvas className={styles.canvas} width=200 height=200></canvas>
    }
}

As for the CSS:

canvas:hover{
  /*cursor:pointer;*/
  cursor:crosshair;
}

Now, I need to dynamically change the CSS based on the value of mode.

If mode is 1, I want to use the pointer cursor style.

Should I just modify the css? or is there another method to achieve this?

Answer №1

Check out the solution provided below. You can also find it in the sandbox.. Please disregard the vanilla react solution included for the snippet runner. Simply click on Run Code Snippet to preview it here.

/* Solution

const ImagePreview = () => {
  const [mode, setMode] = useState(0);
  return (
    <canvas
      onMouseEnter={() => setMode(1)}
      onMouseLeave={() => setMode(0)}
      style={{
        backgroundColor: "teal",
        cursor: mode ? "crosshair" : "pointer"
      }}
      width={200}
      height={200}
    />
  );
};

*/

// This is so it can work in Stackoverflow snippet preview. //
const ImagePreview = () => {
  const [mode, setMode] = React.useState(0);
  const canvasCfg = {
    onMouseEnter: () => setMode(1),
    onMouseLeave: () => setMode(0),
     style: { backgroundColor: "teal", cursor: mode ? "crosshair" : "pointer"},
     width: 200,
     height: 200
  }
  return React.createElement('canvas', canvasCfg)
}

const domContainer = document.querySelector('#app');
const root = ReactDOM.createRoot(domContainer);
root.render(React.createElement(ImagePreview));
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<div id="app"></div>

Answer №2

Generate a pair of classes in the following manner

.hover-effect-1:hover{
    cursor:pointer;
}


.hover-effect-2:hover{
    cursor:crosshair;
}

and implement them conditionally depending on the mode like this

import styles from '../css/basic-styles.module.css';

const ImagePreview = () =>{
    [mode,setMode] = useState(0);
    changeMode(mode){
       setMode(mode);
    }
    return (){
        <canvas className={mode == 1 ? styles.hover-effect-1 : styles.hover-effect-2} width=200 height=200></canvas>
    }
}

You can utilize these classes without :hover as well, since the cursor property will produce the intended outcome

.hover-effect-1{
    cursor: pointer;
}
.hover-effect-2{
    cursor: crosshair;
}

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

The files _buildmanifest.js and _ssgmanifest.js could not be loaded. The server returned a 404 error, indicating that the resources were not found

Upcoming: 12.3.4 React Version: 17.0.2 Node Version: 16.13.1 An error is persisting in my Next.js application where the console displays the following message on all pages I load: 404 Failed to load resource: the server responded with a status of 404 ( ...

What is the best way to pass method props using links in next.js?

I have a navbar component that includes a sign-in link, which is linked to the login page. Within the navbar component, I have a handleLogin function that I want to pass through the link and call in the login component. How can I successfully pass this me ...

Postback does not reload all controls in the NameValueCollection

Recently, I designed a custom User Control in asp.net. public class InputMask : CompositeControl, IPostBackDataHandler, IPostBackEventHandler Imagine the custom control is enclosed within a div element: <div runat="server" id="inputArea"> < ...

Prop in a React component is undergoing mutation

I encountered a strange situation where a prop in a React component is being changed. Although it's technically not a mutation since it's an array in JavaScript, it should not be modified. To replicate the issue, I created a simple example: htt ...

svg viewbox cannot be adjusted in size

Struggling with resizing an SVG to 20px by 20px. The original code size of the SVG is quite large at 0 0 35.41 35.61: <!doctype html> <html> <head> <meta charset="utf-8"> <title>SVG</title> ...

Is there a way to display various data with an onClick event without overwriting the existing render?

In the process of developing a text-based RPG using React/Context API/UseReducer, I wanted to hone my skills with useState in order to showcase objects from an onclick event. So far, I've succeeded in displaying an object from an array based on button ...

The system could not identify 'react-scripts' as a valid command, either internal or external, and the JSON file has been deleted

The error message reads 'react-scripts' is not recognized as an internal or external command, operable program or batch file. I have attempted the following: npm install npm install react-scripts --save npm i -g react-scripts https://github.com/ ...

How to center content vertically in a Bootstrap 5 column div

I assumed that aligning content vertically in a div should be easier compared to using a table: Edit: I want to align the first and last columns while keeping the others as they are. <link href="https://cdn.jsdelivr.net/npm/&l ...

The issue of focus being lost with HOC and Formik

In my latest project, I developed a bootstrap form input component that utilizes HOC (Higher Order Component) to change an icon upon submission. The input validation is done through the Formik library. <InputUi placeholder="Enter your email" ...

Updating Button Text Upon Click

I am looking to create a webpage filled with riddles. After each riddle, there will be an answer button that, when clicked, reveals the answer. Clicking the button again should hide the answer. I attempted to implement this functionality using Javascript, ...

Changing the size of a responsive navigation bar with React and adjusting it based on the window.scrollY position switches between collapsed and un

I'm struggling to create a responsive navbar that automatically adjusts its size once it surpasses the height of the navbar (currently set at 80px). However, when I scroll to around the 80px mark, it starts flickering between the collapsed and expande ...

Issues with the Bootstrap navbar toggle functionality

Hello there! I hope you're doing well. I've been following the Bootstrap 5 tutorial on Traversy media's YouTube channel, but I'm encountering an issue with the nav toggler. The nav is not showing up for me and I can't figure out wh ...

React State incrementing halted at 29

I am currently working on a React project where I need to increase the value of a progress bar using a setProgressBarValue hook. However, I have encountered an issue where the progress bar gets stuck at 29. Here is the code snippet that I am using: const u ...

What are the benefits of using default ES module properties for exporting/importing compared to named module properties?

Currently studying the Material UI documentation, I came across this statement: It is noted in the example above that we used: import RaisedButton from 'material-ui/RaisedButton'; instead of import {RaisedButton} from 'material-ui&apo ...

The Redux state fails to update despite there being no difference between the old and new states

Having trouble with my Redux state. I created a reducer to update a value in an array, following immutability principles. However, the state is not updating as expected. Even added console logs to compare old and new states, but they return false. Any ide ...

Determine the number of items (within an array) that were created within the past few days, weeks, and months leading up to the 'current time'

Having an array filled with objects containing timestamps: Here is a glimpse of the data: const dataList = [ { _id: "602102db3acc4515d4b2f687", createdDt: "2021-02-08T09:22:35.000Z", }, { _id: "6021024da706a260d89 ...

Experiencing difficulties in sending a post request to my express API

I am encountering an issue with my Heroku API where I am not receiving any response after sending a post request. Here is the section of code responsible for making the request: const [ user, setUser] = useState({ email:"", password:"" }) const h ...

The Execution of a Function Fails When Passed to a Functional Component

My functional component accepts a function called addEvent, which expects an event parameter. The problem arises when I try to call this function from props within another functional component, as the function does not seem to execute: const onOk = () =&g ...

The data fetched from an API response does not get displayed by React

I've come across various questions but couldn't find the solution. Below is the code I have: import React, { Component } from "react"; import axios from "axios"; import "./tree.css"; import "./mainTree"; class TablesTree extends Component { c ...

I am experiencing some layout problems with Joomla K2

Having some alignment issues in the header section of my article. I took a screenshot, but you can also check out the live page here. See the pic below: Upon inspecting the area I wanted to adjust, I discovered: span.itemAuthorDetailss position: relativ ...