Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

WikiQuora

WikiQuora Logo WikiQuora Logo

WikiQuora Navigation

Search
Ask A Question

Mobile menu

Close
Ask A Question
  • Home
  • Add group
  • Feed
  • User Profile
  • Communities
  • Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
Home/javascript

WikiQuora Latest Questions

W3spoint99
  • 0
W3spoint99Begginer
Asked: January 17, 2025In: Reactjs

How to programmatically navigate using React Router?

  • 0

How to programmatically navigate using React Router? With react-router I can use the Link element to create links which are natively handled by react router. I see internally it calls this.context.transitionTo(...). I want to do a navigation. Not from a link, but from a dropdown selection (as an ...

javascriptreact routerreactjs
  1. Saralyn
    Saralyn Teacher
    Added an answer on January 17, 2025 at 2:00 pm

    The useHistory() hook is now deprecated. If you are using React Router 6, the proper way to navigate programmatically is as follows: import { useNavigate } from "react-router-dom"; function HomeButton() { const navigate = useNavigate(); function handleClick() { navigate("/home"); } return ( <buttRead more

    The useHistory() hook is now deprecated. If you are using React Router 6, the proper way to navigate programmatically is as follows:

    import { useNavigate } from "react-router-dom";
    
    function HomeButton() {
      const navigate = useNavigate();
    
      function handleClick() {
        navigate("/home");
      }
    
      return (
        <button type="button" onClick={handleClick}>
          Go home
        </button>
      );
    }
    
    

    React Router v5.1.0 with hooks

    There is a new useHistory hook in React Router >5.1.0 if you are using React >16.8.0 and functional components.

    import { useHistory } from "react-router-dom";
    
    function HomeButton() {
      const history = useHistory();
    
      function handleClick() {
        history.push("/home");
      }
    
      return (
        <button type="button" onClick={handleClick}>
          Go home
        </button>
      );
    }
    

    React Router v4

    With v4 of React Router, there are three approaches that you can take to programmatic routing within components.

    1. Use the withRouter higher-order component.
    2. Use composition and render a <Route>
    3. Use the context.

    React Router is mostly a wrapper around the history library. history handles interaction with the browser’s window.history for you with its browser and hash histories. It also provides a memory history which is useful for environments that don’t have a global history. This is particularly useful in mobile app development (react-native) and unit testing with Node.

    A history instance has two methods for navigating: push and replace. If you think of the history as an array of visited locations, push will add a new location to the array and replace will replace the current location in the array with the new one. Typically you will want to use the push method when you are navigating.

    In earlier versions of React Router, you had to create your own history instance, but in v4 the <BrowserRouter>, <HashRouter>, and <MemoryRouter> components will create a browser, hash, and memory instances for you. React Router makes the properties and methods of the history instance associated with your router available through the context, under the router object.

    1. Use the withRouter higher-order component

    The withRouter higher-order component will inject the history object as a prop of the component. This allows you to access the push and replace methods without having to deal with the context.

    import { withRouter } from 'react-router-dom'
    // this also works with react-router-native
    
    const Button = withRouter(({ history }) => (
      <button
        type='button'
        onClick={() => { history.push('/new-location') }}
      >
        Click Me!
      </button>
    ))
    

    2. Use composition and render a <Route>

    The <Route> component isn’t just for matching locations. You can render a pathless route and it will always match the current location. The <Route> component passes the same props as withRouter, so you will be able to access the history methods through the history prop.

    import { Route } from 'react-router-dom'
    
    const Button = () => (
      <Route render={({ history}) => (
        <button
          type='button'
          onClick={() => { history.push('/new-location') }}
        >
          Click Me!
        </button>
      )} />
    )
    

    3. Use the context*

    But you probably should not

    The last option is one that you should only use if you feel comfortable working with React’s context model (React’s Context API is stable as of v16).

    const Button = (props, context) => (
      <button
        type='button'
        onClick={() => {
          // context.history.push === history.push
          context.history.push('/new-location')
        }}
      >
        Click Me!
      </button>
    )
    
    // you need to specify the context type so that it
    // is available within the component
    Button.contextTypes = {
      history: React.PropTypes.shape({
        push: React.PropTypes.func.isRequired
      })
    }
    

    1 and 2 are the simplest choices to implement, so for most use cases, they are your best bets.

    See less
      • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
1
  • 1 1 Answer
  • 291 Views
Answer
W3spoint99
  • 0
W3spoint99Begginer
Asked: December 30, 2024In: Javascript

How to remove a specific item from an array in JavaScript?

  • 0

How do I remove a specific value from an array? Something like: array.remove(value); Constraints: I have to use core JavaScript. Frameworks are not allowed.

arraysitemjavascriptremove
  1. Saralyn
    Saralyn Teacher
    Added an answer on December 30, 2024 at 7:37 am
    This answer was edited.

    Find the index of the array element you want to remove using indexOf, and then remove that index with splice. The splice() method changes the contents of an array by removing existing elements and/or adding new elements. const array = [2, 5, 9]; console.log(array); const index = array.indexOf(5); ifRead more

    Find the index of the array element you want to remove using indexOf, and then remove that index with splice.

    The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

    const array = [2, 5, 9];
    
    console.log(array);
    
    const index = array.indexOf(5);
    if (index > -1) { // only splice array when item is found
      array.splice(index, 1); // 2nd parameter means remove one item only
    }
    
    // array = [2, 9]
    console.log(array);

    The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.


    For completeness, here are functions. The first function removes only a single occurrence (e.g., removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences:

    function removeItemOnce(arr, value) {
      var index = arr.indexOf(value);
      if (index > -1) {
        arr.splice(index, 1);
      }
      return arr;
    }
    
    function removeItemAll(arr, value) {
      var i = 0;
      while (i < arr.length) {
        if (arr[i] === value) {
          arr.splice(i, 1);
        } else {
          ++i;
        }
      }
      return arr;
    }
    // Usage
    console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
    console.log(removeItemAll([2,5,9,1,5,8,5], 5))

    In TypeScript, these functions can stay type-safe with a type parameter:

    function removeItem<T>(arr: Array<T>, value: T): Array<T> {
      const index = arr.indexOf(value);
      if (index > -1) {
        arr.splice(index, 1);
      }
      return arr;
    }
    See less
      • 0
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report
1
  • 1 1 Answer
  • 278 Views
Answer

Sidebar

Ask A Question
  • Popular
  • Answers
  • W3spoint99

    What is the difference between Promises and Observables?

    • 2 Answers
  • W3spoint99

    Can't bind to 'ngModel' since it isn't a known property ...

    • 2 Answers
  • W3spoint99

    How to prevent SQL injection in PHP?

    • 1 Answer
  • Saralyn
    Saralyn added an answer Learn Java if: ✅ You want to work on enterprise applications.… April 27, 2025 at 2:01 pm
  • Saralyn
    Saralyn added an answer AI is getting smarter, but replacing programmers entirely? That’s not… April 27, 2025 at 1:58 pm
  • Saralyn
    Saralyn added an answer Both Promises and Observables provide us with abstractions that help us deal with the asynchronous nature… January 17, 2025 at 2:03 pm

Trending Tags

AI angular application.properties arrays artificial intelligence coding how Java javascript machine learning mysql nullpointerexception php programmer python reactjs spring springboot sql string

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

  • About US
  • Privacy Policy
  • Questions
  • Recent Questions
  • Web Stories

© 2025 WikiQuora.Com. All Rights Reserved