Reputation: 5099
I am trying to send parameter to click event from anchor element, is it possible of we should not pass params at all?
here is my function:
const slideShow = (e: React.MouseEvent<HTMLAnchorElement> | undefined): void => {
console.log(e);
}
html :
<div className="slider">
<a className="prev" onClick={slideShow}>Previous</a>
<h2>Barking Road, London</h2>
<a className="next" onClick={slideShow}>Next</a>
</div>
but when user click on prev
link i would like to send -1
and for the next
with 1
as parameter. is there any way? or totally it's not applicable?
Upvotes: 1
Views: 4863
Reputation: 4974
It's better to use a state
for your aim:
import { useEffect, useState } from "react";
export default function App() {
const [value, setValue] = useState(0);
useEffect(() => {
console.log(value);
}, [value]);
const slideShow = (
e: React.MouseEvent<HTMLAnchorElement> | undefined,
value: number
): void => {
e?.preventDefault();
setValue(value);
};
return (
<div className="slider">
<a href="/" className="prev" onClick={ (e) => slideShow(e, -1) }>
Previous
</a>
<h2>Barking Road, London</h2>
<a href="/" className="next" onClick={ (e) => slideShow(e, 1) }>
Next
</a>
</div>
);
}
Upvotes: 1
Reputation: 1116
const slideShow = (e: React.MouseEvent<HTMLAnchorElement> | undefined): void => {
console.log(e.currentTarget.dataset.step);
// do something with step parameter
}
<div className="slider">
<a data-step={-1} className="prev" onClick={slideShow}>Previous</a>
<h2>Barking Road, London</h2>
<a data-step={1} className="next" onClick={slideShow}>Next</a>
</div>
const slideShow = (step: number) => (e: React.MouseEvent<HTMLAnchorElement> | undefined): void => {
console.log(step);
// do something with step parameter
}
// above function is like:
const slideShow = (step: number) => {
return (e: React.MouseEvent<HTMLAnchorElement> | undefined): void => {
console.log(step);
// do something with step parameter
}
}
<div className="slider">
<a className="prev" onClick={slideShow(-1)}>Previous</a>
<h2>Barking Road, London</h2>
<a className="next" onClick={slideShow(1)}>Next</a>
</div>
const slideShow = (step: number): void => {
console.log(step);
// do something with step parameter
}
<div className="slider">
<a className="prev" onClick={() => slideShow(-1)}>Previous</a>
<h2>Barking Road, London</h2>
<a className="next" onClick={() => slideShow(1)}>Next</a>
</div>
Upvotes: 2
Reputation: 819
It is easy to send parameter to function just instead of:
<a className="prev" onClick={slideShow}>Previous</a>
use:
<a className="prev" onClick={(e) =>{slideShow(e, -1)}}>Previous</a>
having:
const slideShow = (e: React.MouseEvent<HTMLAnchorElement> | undefined, value:number): void => {
console.log(e, number);
}
Upvotes: -1