react редирект при клике

How to redirect to a new page from a function in React?

Right now I have this function in react and I am using it to go back to login and also to check reset the localStorage value for which I am using the function and not since using that I cannot reset local storage value. The function is below:-

This gets executed on clicking a div but I am not able to go to the /login page.How to do it?

13 Answers 13

With all previous answers, I’ll describe here this use case:

Add in your component default state a redirect to false:

Add to your business logic (ex. onLoginOk() ) a change of the redirect state

Add somewhere in your render root element:

you can use this example for redirect after rendering a function

react редирект при клике. Смотреть фото react редирект при клике. Смотреть картинку react редирект при клике. Картинка про react редирект при клике. Фото react редирект при клике

You can use history variable in props or if haven’t history in props, you can use withRouter HOC (https://reacttraining.com/react-router/web/api/withRouter)

Maybe that’s what you are looking for.

If you are trying to logout in a React application (that uses the URL pattern /#/page ) through a function that clean the local storage / redirect, try to use go :

The go loads a specific URL from the history list, this can be used to go back in the history, but also to go foward, in this case the ‘foward’ will use /login and the absolute path to redirect.

Update

On React Router 6 you can use useNavigate to navigate programmatically

Источник

How to use Redirect in the new react-router-dom of Reactjs

I am using the last version react-router module, named react-router-dom, that has become the default when developing web applications with React. I want to know how to make a redirection after a POST request. I have been making this code, but after the request, nothing happens. I review on the web, but all the data is about previous versions of the react router, and no with the last update.

14 Answers 14

You have to use setState to set a property that will render the inside your render() method.

That said, I would suggest you to put the API call inside a service or something. Then you could just use the history object to route programatically. This is how the integration with redux works.

But I guess you have your reasons to do it this way.

react редирект при клике. Смотреть фото react редирект при клике. Смотреть картинку react редирект при клике. Картинка про react редирект при клике. Фото react редирект при клике

Here a small example as response to the title as all mentioned examples are complicated in my opinion as well as the official one.

You should know how to transpile es2015 as well as make your server able to handle the redirect. Here is a snippet for express. More info related to this can be found here.

Make sure to put this below all other routes.

React Router v5 now allows you to simply redirect using history.push() thanks to the useHistory() hook:

react редирект при клике. Смотреть фото react редирект при клике. Смотреть картинку react редирект при клике. Картинка про react редирект при клике. Фото react редирект при клике

Simply call it inside any function you like.

react редирект при клике. Смотреть фото react редирект при клике. Смотреть картинку react редирект при клике. Картинка про react редирект при клике. Фото react редирект при клике

Try something like this.

react редирект при клике. Смотреть фото react редирект при клике. Смотреть картинку react редирект при клике. Картинка про react редирект при клике. Фото react редирект при клике

you can write a hoc for this purpose and write a method call redirect, here is the code:

react редирект при клике. Смотреть фото react редирект при клике. Смотреть картинку react редирект при клике. Картинка про react редирект при клике. Фото react редирект при клике

The simplest solution to navigate to another component is( Example navigates to mails component by click on icon):

Источник

Redirecting in React

Sometimes you just want to get away…

Jul 26, 2017 · 3 min read

Single page websites are great because they dynamically update as the user interacts with application, thus allowing for shorter loading times between pages. Although the page never actually reloads or sends you to a new route, the app mimics this behavior by manipulating the window’s history or location objects. Using a link to navigate to a new page with is pretty straightforward: a user interacts with an element, and that event triggers the history or location change. Redirecting proves to be more difficult, as the routing action needs to be fired based on the state of the application.

Redirect Component

If you have routes in your React app, you’re probably using React Router (or React Router DOM) to set up your routes. Considering you’ve already installed the React Router library, the easiest way to redirect to a new location is by using its Redirect component. When the component is rendered, the existing location of the history object is replaced with a new location. If you don’t want to override the existing history location, including the push property will push a new entry onto the history.

This route (haha) is not the best if you’re not a fan of controlled components, that is, it has and is responsible for its own state. Luckily, we can still accomplish this behavior manually by passing props!

Route Component Props

The Route component provides three props to whatever component it renders: location, match and history. Passing down these props to a nested component gives us access to the history object, which we can then push a new location onto.

But what if the component that needs the redirect functionality is nested super deep? Passing these props through all the components between the route and your child component is not ideal, so here is a third (but not recommended) option: Context and PropTypes

Источник

Как использовать Redirect в новом реале-маршрутизаторе Reactjs

Я использую модуль реакции-маршрутизатора последней версии, названный реагировать-маршрутизатор-дом, который стал по умолчанию при разработке веб-приложений с React. Я хочу знать, как сделать перенаправление после запроса POST. Я делал этот код, но после запроса ничего не происходит. Я просматриваю в Интернете, но все данные о предыдущих версиях реагирующего маршрутизатора, а не о последнем обновлении.

ОТВЕТЫ

Ответ 1

Тем не менее, я бы посоветовал вам поместить вызов API в сервис или что-то в этом роде. Тогда вы можете просто использовать объект history для программной маршрутизации. Вот как работает интеграция с Redux.

Но я думаю, у тебя есть причины сделать это таким образом.

Ответ 2

Вот небольшой пример в ответ на название, так как все упомянутые примеры сложны, на мой взгляд, так же, как и официальный.

Вы должны знать, как переносить es2015, а также чтобы ваш сервер мог обрабатывать перенаправление. Вот фрагмент для экспресса. Дополнительную информацию, связанную с этим, можно найти здесь.

Не забудьте указать это ниже всех других маршрутов.

Ответ 3

Просто вызовите его внутри любой функции, которая вам нравится.

Ответ 4

Попробуйте что-нибудь подобное.

Ответ 5

Ответ 6

Ответ 7

Для перехода к другому компоненту вы можете использовать this.props.history.push(‘/main’);

Ответ 8

Вы можете написать hoc для этой цели и написать перенаправление вызова метода, вот код:

Ответ 9

Самым простым решением для перехода к другому компоненту является (например, переход к компоненту почты с помощью значка):

Ответ 10

Кроме того, вы можете использовать условный рендеринг React.

Ответ 11

React Router v5 теперь позволяет вам просто перенаправлять с помощью history.push() благодаря хуку useHistory():

Ответ 12

Я попробовал простой взлом. Может не хорошо, но это работает для меня. Я написал этот простой код внутри событий. Это перенаправит на конкретное местоположение браузера ( /path )

Источник

React onClick and preventDefault() link refresh/redirect?

I’m rendering a link with react:

Then, above I have the upvote function:

I’ve also tried all of the above using jQuery in my index.html, but nothing seems to work. What should I do here and what I’m doing wrong? I’ve checked event.type and it’s click so I guess I should be able to avoid redirect somehow?

Excuse me, I’m a rookie when it comes to React.

14 Answers 14

A full version of the solution will be wrapping the method upvotes inside onClick, passing e and use native e.preventDefault();

react редирект при клике. Смотреть фото react редирект при клике. Смотреть картинку react редирект при клике. Картинка про react редирект при клике. Фото react редирект при клике

React events are actually Synthetic Events, not Native Events. As it is written here:

Event delegation: React doesn’t actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React’s event handlers are simple no-ops.

Try to use Use Event.stopImmediatePropagation :

react редирект при клике. Смотреть фото react редирект при клике. Смотреть картинку react редирект при клике. Картинка про react редирект при клике. Фото react редирект при клике

or if you are writing in es6 react component in constructor you could do this

In a context like this

As you can see, you have to call preventDefault() explicitly. I think that this docs, could be helpful.

react редирект при клике. Смотреть фото react редирект при клике. Смотреть картинку react редирект при клике. Картинка про react редирект при клике. Фото react редирект при клике

The Gist I found and works for me:

react редирект при клике. Смотреть фото react редирект при клике. Смотреть картинку react редирект при клике. Картинка про react редирект при клике. Фото react редирект при клике

A nice and simple option that worked for me was:

This is because those handlers do not preserve scope. From react documentation: react documentation

Check the «no autobinding» section. You should write the handler like: onClick = () => <>

I didn’t find any of the mentioned options to be correct or work for me when I came to this page. They did give me ideas to test things out and I found that this worked for me.

If you use checkbox

stopPropagation and stopImmediatePropagation won’t be working.

Because you must using onClick=

If you are using React Router, I’d suggest looking into the react-router-bootstrap library which has a handy component LinkContainer. This component prevents default page reload so you don’t have to deal with the event.

In your case it could look something like:

react редирект при клике. Смотреть фото react редирект при клике. Смотреть картинку react редирект при клике. Картинка про react редирект при клике. Фото react редирект при клике

I’ve had some troubles with anchor tags and preventDefault in the past and I always forget what I’m doing wrong, so here’s what I figured out.

The problem I often have is that I try to access the component’s attributes by destructuring them directly as with other React components. This will not work, the page will reload, even with e.preventDefault() :

It seems the destructuring causes an error ( Cannot read property ‘href’ of undefined ) that is not displayed to the console, probably due to the page complete reload. Since the function is in error, the preventDefault doesn’t get called. If the href is #, the error is displayed properly since there’s no actual reload.

I understand now that I can only access attributes as a second handler argument on custom React components, not on native HTML tags. So of course, to access an HTML tag attribute in an event, this would be the way:

I hope this helps other people like me puzzled by not shown errors!

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *