Reputation: 874
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…"/>
<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.
Upvotes: 1
Views: 5452
Reputation: 874
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>
)
}
Upvotes: 2
Reputation: 66
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…"
/>
<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)
Upvotes: 5