Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a button redirect to another page in React

I have a component which has in its Class.propTypes a function onClick: onClick: PropTypes.func

In another component I'm using this component multiple times to populate a page. Each of these components have a title which when clicked should redirect to another page.

The problem I have is that it doesn't work when I click on it. It does nothing. This is the render of the main component:

render() {
    return (
            <Class
    title={account.AccountName}
    onClick={() => "mySite/accountview?id=" + account.AccountName} 
         >
         </Class>
          ...
    );
}

What should I add to onClick to make it work?

like image 290
Samurai Jack Avatar asked Jun 21 '17 13:06

Samurai Jack


People also ask

How do you make a button go to another page in react?

To redirect to another page on button click in React: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function, passing it the path - navigate('/about') . The navigate() function lets us navigate programmatically.

How do you navigate onClick in react?

To navigate to the courses route, we will use the history. push method of the useHistory object. We will add an event handler “onClick” for our button component and define a function “coursesPage ” that handles the click event. The coursesPage function enables us to redirect to another route on clicking the button.


1 Answers

You need use React Router.

With Link:

<Link to={`/mySite/accountview?id=${account.AccountName}`}>something</Link>

With onClick:

<button onClick={() => hashHistory.push(`/mySite/accountview?id=${account.AccountName}`)}></button>

You can use hashHistory or browserHistory :D

like image 110
Gabriel Ferreira Avatar answered Sep 30 '22 08:09

Gabriel Ferreira