Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In reactJS, how to invoke link click via button press?

Tags:

reactjs

I have a button. When the users presses it, I want the outcome ot be the same as if the user had pressed a specific link.

Put another way, I want to represent a link as a button.

I can see from this that it is possible using Jquery: How to call a href by onclick event of a button?

What is the "correct" way to do this in ReactJS?

like image 573
Duke Dougal Avatar asked Dec 10 '16 21:12

Duke Dougal


People also ask

How do I open a link in click of button in React JS?

To use a button as a link in React, wrap the button in an <a> tag or a Link component if using react router. The button will get rendered instead of the link and clicking on it will cause the browser to navigate to the specified page. Copied!


Video Answer


2 Answers

Like this:

<button     type="button"     onClick={(e) => {       e.preventDefault();       window.location.href='http://google.com';       }} > Click here</button> 
like image 163
jmunox Avatar answered Sep 29 '22 08:09

jmunox


Use React-Router Link,instead of Anchor tag.

import React, { Component } from 'react';  import {Link} from 'react-router-dom'   // reactClass --      return (        <div>        <Link to='https://react.semantic-ui.com/'>        <button type="button" className="btn btn-info">Button</button>        </Link>        </div>      );    // end--
like image 38
Saurabh Avatar answered Sep 29 '22 09:09

Saurabh