I have a button element in React page. With onclick event I called a function from my context. Now I want to add a href in that button.
Here is my code:
{ categoryData.map((item,index)=>{
return(
<button className="dropdown-item" to={/articles/${item}} onClick={updateFilterValue} key={index} name="category" value={item}>{ item }</button>
)
})}
This is my updateFilterValue function:
const updateFilterValue = (event) => {
let name = event.target.name;
let value = event.target.value;
return dispatch({ type: "UPDATE_FILTERS_VALUE", payload: { name, value } });
};
Basically onclick will pass the name and value attribute to updateFilterValue function. I am getting this updateFilterValue from my context. Now at the same time I want to redirect to /articles/${item}
route. How to do that?
4
Answers
If you want to go to the route with the item on click, you can use the Navigate element of the react-router dom you can simple have this inside your function.
You can refer here for Navigate docs
Inside
updateFilterValue
function, you can setwindow.location.href = "/articles/${item}"
so that after the code of your function you get redirected to that route.Hope it helps.
You can achieve this by Without using any Routing Libraby
Just Add
<a href="/your-RouteAddress">{item}</a>
Your Code Look Like :-
You Also Can Use Link to achieve this By Using Link Tag.
You Need to Import Link Tag
import { Link } from "react-router-dom";
And Your Code Will be
Two ways to do this depending on your requirement.
First Method
and the Second Method will be: