35

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?

Community
  • 1
  • 1
Duke Dougal
  • 21,281
  • 28
  • 79
  • 112

5 Answers5

36

Like this:

<button
    type="button"
    onClick={(e) => {
      e.preventDefault();
      window.location.href='http://google.com';
      }}
> Click here</button>
Suz
  • 73
  • 1
  • 6
jmunox
  • 369
  • 3
  • 3
17

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--
Saurabh
  • 717
  • 5
  • 15
4

You don't even need jQuery nor React to do that. It's as simple as this:

var ex = document.getElementById('ex');
ex.onclick = function(){
  console.log('clicked');
}

var bt = document.getElementById('bt');
bt.onclick = function(){
  ex.click();
}
<button id="bt">Click</button>
<a id="ex">Triggerable link</a>

Of course, in React you can store the ref of the components, bind to the event and then trigger the event like this:

onClick(){
    this.ex.click();
}
render(){
    return (
        <div>
          <button id="bt" onClick={this.onClick.bind(this)} ref={(ref)=>{this.bt = ref}}>Click</button>
          <a id="ex" onClick={()=>console.log("clicked")} ref={(ref)=>{this.ex = ref}}>Triggerable link</a>
        </div>
    )
}

Edit: If you just want a button that behaves like a link, you can use this, or any of the solutions listed in this question:

onClick(){
    window.location.href="http://url.com";
}
render(){
    return (
        <button id="bt" onClick={this.onClick}>Click</button>
    )
}
martinarroyo
  • 8,923
  • 3
  • 33
  • 73
0

2021 Update :

<div
    style={{
      width: 15,
      height: 15,
      background: "blue",
      cursor: "pointer",
    }}
    onClick={() => {
      window.open("http://google.com", "_blank");
    }}
  />
Ghassane AB
  • 139
  • 3
  • 5
0

This worked for me :)

<a target="_blank" href="http://google.com"> <button id="bt" >Click</button> </a>

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 19 '21 at 10:36