简体   繁体   中英

How to modify an element through a different element's onClick in nextjs?

import Link from 'next/link';

function myClick(e){
  console.log(e);
}

const Index = () => (
        <section className="min-vh-100">
            <div className="input_bar border rounded-maximum p-1 mx-1 bg-white d-flex">
                <input className="myButton submit_bar text-black" placeholder="Insert your input&hellip;"/>
                <Link href="#"><a onClick={myClick} className="input_icon"></a></Link>
            </div>
        </section>
);

I'm using nextjs and I'm trying to change a div's class through a click function in another div, I couldn't find examples of how to do that so I can understand how it works. Thank you.

Here is an example using refs:

import Link from 'next/link'

const Index = () => {
  let myDiv = React.createRef()

  function myClick() {
    myDiv.current.classList.add('add-this-class')
  }

  return (
    <section className="min-vh-100">
      <div
        ref={myDiv}
        className="input_bar border rounded-maximum p-1 mx-1 bg-white d-flex"
      >
        <input
          className="myButton submit_bar text-black"
          placeholder="Insert your input&hellip;"
        />
        <Link href="#">
          <a onClick={myClick} className="input_icon" />
        </Link>
      </div>
    </section>
  )
}

To understand what I'm doing here. I'm creating a reference with this line:

let myDiv = React.createRef()

Then I assign it to the element I want to access, in the example I assign it to the div:

<div ref={myDiv} className="..." >

And on the onClick function I access the div and add a class:

myDiv.current.classList.add('add-this-class')

Let me know if this works for you. (If it did, thank Abderrahman)

I used hooks .

const Index = () => {
    const [className, setClassName] = useState("")

    const myClick = () => {
        setClassName("some-class")
    }

    return (
        <div>
            <button onClick={myClick}>Click me</button>
            <div className={className}>Classname gets changes</div>
        </div>
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM