0

I'm building this code in when a user clicks the image, it should assign the newstyle to the style state. But whenever I click in a position of the image, it pops up an newStyle is undefined error even when I've set the variable newStyle inside the imageClick function.

import React, {useState} from 'react'
import mainImage from '../img/marioBrosMain.jpg'
import '../main.css'
import Box from '../pages/box.js'

function Main() {

  const [style, setStyle] = useState();

  const imageClick = (x, y) => {
    const newStyle = `position: absolute,
    z-index: 2,
    border-radius: 2px solid red,
    border: 2px solid red,
    height: 50px,
    padding-left: 50px,
    margin-left: 1450px,
            left:${x}px,
            top:${y}px`
    return newStyle
  }

    return (
        <div id="frame">
          <div id="mainImage" style = {style}></div>
          <img src={mainImage} className="marioBros____image" onClick={e => {
          imageClick(e.screenX, e.screenY);
           setStyle(newStyle);
        }}/>
        </div>
    )
}

export default Main
Chen
  • 281
  • 5
  • 14

2 Answers2

2

It looks like newStyle is not in scope in the code you have posted. Maybe something like this would work:

 <img 
    src={mainImage} 
    className="marioBros____image" 
    onClick={e => setStyle(imageClick(e.screenX, e.screenY)) }
 />

This way you're directly setting the style with the return value from imageClick.

Chris Farmer
  • 24,974
  • 34
  • 121
  • 164
0

I think this is the optimal code.

import React, { useState } from "react"
import mainImage from "../img/marioBrosMain.jpg"
import "../main.css"
import Box from "../pages/box.js"

export default function Main() {
  const [style, setStyle] = useState()

  const imageClick = (x, y) => ({
    position: "absolute",
    zIndex: 2,
    borderRadius: 2,
    borderColor: "red",
    borderStyle: "solid",
    height: 50,
    paddingLeft: 50,
    marginLeft: 1450,
    left: x,
    top: y
  })

  return (
    <div id="frame">
      <div id="mainImage" style={{}}></div>
      <img src={mainImage} className="marioBros____image" onClick={e => setStyle(imageClick(e.screenX, e.screenY))} />
    </div>
  )
oxygen
  • 103
  • 5