Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anchor tag isn't calling the onClick function in React

I'm trying to update my component state when you click on an anchor tag inside the render method. I've tried binding inside the constructor, but still the console.log isn't being called. Below is my code. Please help. This is holding me back from progressing lol.

This is modified code based on my previous question here on stackoverflow.

const React = require('react');


class Navbar extends React.Component {
  constructor(...props) {
    super(...props);
    this.setActiveTab = this.setActiveTab.bind(this)
    this.state = {
      currentPage: "/"
    }
  }

  setActiveTab(e) {
    console.log(e.target)
    this.setState({
      currentPage: e.target.href 
    })
  }

  render() {
    const { path } = this.props
    let classString = path === this.state.currentPage ? 'nav-item is-tab is-active' : 'nav-item is-tab'

    return (
      <nav className="nav">

        <div className="nav-left">
          <a className="nav-item">
            <h1>CREATORS NEVER DIE</h1>
          </a>
        </div>

        <div className="nav-right nav-menu">
          <a href="/" className={classString} onClick={this.setActiveTab}>
            Home
          </a>
        </div>


      </nav>
    )
  }
}

module.exports = Navbar;
like image 311
Dileet Avatar asked May 31 '17 18:05

Dileet


People also ask

Can I use onClick in anchor tag React?

The React onClick event handler enables you to call a function and trigger an action when a user clicks an element, such as a button, in your app. Event names are written in camelCase, so the onclick event is written as onClick in a React app. In addition, React event handlers appear inside curly braces.

How do you call onClick in a tag function?

Try onclick function separately it can give you access to execute your function which can be used to open up a new window, for this purpose you first need to create a javascript function there you can define it and in your anchor tag you just need to call your function.


3 Answers

You need e.preventDefault() in the click handler.

It's firing but the default behavior of an anchor is to refresh the page, so it's just rerendering immediately.

like image 92
aaronjkrause Avatar answered Oct 13 '22 03:10

aaronjkrause


Check the working snippet, both the ways are working, either remove the href or use href='javascript:void(0)' console is printing the proper value on click of Home:

class Navbar extends React.Component {
    constructor() {
      super();
      this.setActiveTab = this.setActiveTab.bind(this)
      this.state = {
         currentPage: '',
      }
  }

  setActiveTab(e) {
      console.log(e.target);
  }

  render() {
      return (
         <div className="nav-right nav-menu">
           
            <a onClick={this.setActiveTab}>
               Home1
            </a>

            <br/>

            <a href='javascript:void(0)' onClick={this.setActiveTab}>
              Home2
            </a>
          
         </div>
      )
   }
}

ReactDOM.render(<Navbar/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>
like image 27
Mayank Shukla Avatar answered Oct 13 '22 02:10

Mayank Shukla


Researching the issue it appears you need to prevent the default of the anchor tag. Also if you create an arrow function you are able to handle the this.

Prevent default info can be found on React docs here

Hope this helps.

 const React = require("react");

class Navbar extends React.Component {
    constructor(...props) {
        super(...props);
        this.setActiveTab = this.setActiveTab.bind(this);
        this.state = {
            currentPage: "/",
        };
    }

    setActiveTab = (e) => {
        e.preventDefault();
        console.log(e.target);
        this.setState({
            currentPage: e.target.href,
        });
    }

    render() {
        const { path } = this.props;
        let classString =
            path === this.state.currentPage ? "nav-item is-tab is-active" : "nav-item is-tab";

        return (
            <nav className="nav">
                <div className="nav-left">
                    <a className="nav-item">
                        <h1>CREATORS NEVER DIE</h1>
                    </a>
                </div>

                <div className="nav-right nav-menu">
                    <a href="/" className={classString} onClick={this.setActiveTab}>
                        Home
                    </a>
                </div>
            </nav>
        );
    }
}

module.exports = Navbar;
like image 25
mjbryan10 Avatar answered Oct 13 '22 04:10

mjbryan10