Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

197
Vistas
Proceed to NavLink Conditionally

I would like to click on the NavLink component without immediately proceeding to the path that I set for it. Upon clicking on NavLink, I need to check a condition and, if it is true, set state. If it is false, then only proceed to NavLink path.

NOTE: I do NOT want to use history.push("/path"). I want to do this using NavLink only.

import React from "react";
import {NavLink} from "react-router-dom";

class SomePage extends React.Component {
  constructor() {
    super();
    this.state = {
      someVar: false
    };
  }

  someFunction = () => {
     //does some stuff
 }

  onClick = () => {

    someFunction().then( someBool => {
     if(someBool !== undefined) {
         e.preventDefault();             // not working
         setState({someVar: true})
     }
    })

  };

  render() {
    return (
      <div className="App">
        <form>
            <NavLink to="/anotherPage" onClick={this.onClick}>
              Another Page
            </NavLink>
        </form>
      </div>
    );
  }
}
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Let your onClick handler consume the click event, and under the correct condition prevent the default action (and event propagation, if necessary).

Example:

class SomePage extends React.Component {
  constructor() {
    super();
    this.state = {
      someVar: false
    };
  }

  onClick = (e) => {
    if (thing is true) {
      e.preventDefault(); // <-- prevent link navigation from occurring
      this.setState({ someVar: true });
    } else {
      // allow link navigation to occur
      // proceed to NavLink 
      // this else might not be necessary if it doesn't do anything
      // other than allow the navigation to occur
    }
  };

  render() {
    return (
      <div className="App">
        <form>
          <NavLink to="/anotherPage" onClick={this.onClick}>
            Another Page
          </NavLink>
        </form>
      </div>
    );
  }
}

Update

Since it seems the click handler uses asynchronous code you'll need to entirely prevent the default link action and conditionally issue an imperative navigation action via the history.push.

class SomePage extends React.Component {
  constructor() {
    super();
    this.state = {
      someVar: false
    };
  }

  someFunction = async () => { // <-- returns Promise
    //does some stuff
  }

  onClick = target => async (e) => {
    e.preventDefault();

    try {
      const someBool = await someFunction();
      if (someBool !== undefined) {
        setState({ someVar: true });
      } else {
        this.props.history.push(target);
      }
    } catch(error) {
      // catch and handle any errors/rejected Promises, etc...
    }
  };

  render() {
    return (
      <div className="App">
        <form>
          <NavLink to="/anotherPage" onClick={this.onClick("/anotherPage")}>
            Another Page
          </NavLink>
        </form>
      </div>
    );
  }
}
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda