How to use onClick event on Link: ReactJS? - reactjs

In React router, I have to and onClick attributes as shown below
<li key={i}><Link to="/about" onClick={() => props.selectName(name)}>{name}</Link></li>
state = {
selectedName: ''
};
selectName = (name) => {
setTimeout(function(){this.setState({selectedName:name});}.bind(this),1000);
// this.setState({selectedName: name});
}
to attribute navigates to about Route
onClick assigns value to state variable selectedName which will be displayed when navigated to About page.
When I give timeout insided function called on click, its navigating to new page and after sometime state is getting updated resulting in displaying previous name until state is updated with new name.
Is there a way where it will navigate to the new route only after the code in onClick function gets executed.
You can get the entire code [here].(https://github.com/pushkalb123/basic-react-router/blob/master/src/App.js)

One possible way is, Instead of using Link, use history.push to change the route dynamically. To achieve that remove the Link component and define the onClick event on li. Now first perform all the task inside onClick function and at the end use history.push to change the route means to navigate on other page.
In your case change the router inside setState callback function to ensure that it will happen only after state change.
Write it like this:
<li key={i} onClick={() => props.selectName(name)}> {name} </li>
selectName = (name) => {
this.setState({ selectedName:name }, () => {
this.props.history.push('about');
});
}
Check this answers for:
When to use setState callback
How to navigate dynamically using react router dom

Alternatively, I would recommend using URL Params in order to capture the name of the person that the about page is about. Thus, instead of the url being /about and the name being behind the scenes, it would be /about/tom or /about/pushkal. The way that you do this is by defining params in the URL router as such in your index.js:
<Route path="/about/:name" component={AboutPage}>
Now, when you link to the about page, you would do it as such:
<Link to={"/about/" + name}>{name}</Link>
Now, in your AboutPage component, you can access the name param as a prop in this.props.params.name. You can look at more examples here.
This method is a bit different than your current approach but I suspect it will lead to easier design later on

Related

Dealing with "empty" anchor tags while using HashRouter from React Router

I'm using electron-react-boilerplate and I've had some difficulty getting started with the BrowserRouter from react-router-dom. I opted to use the HashRouter instead and it works much better.
For context, I am building a note-taking application.
There are some instances where I have anchor tags like this:
// list of notes
notes.forEach(note => <a href="#" onClick={handleClick}>{note.title}</a>);
However, when I'm on the file:///home/grapefruit/my_app/src/index.html#/notes route, clicking the anchor tag (with href="#") obviously sends me back to the "root" route (file:///home/grapefruit/my_app/src/index.html#/).
I am looking for ways to prevent this from happening. The route should not change when the user chooses a note to view. Instead, the onClick handler changes the activeNote state, which determines the note to be shown in the right-hand pane.
I could do this (which does work), but instinctively it feels like a bad approach:
const a = document.getElementsByTagName('a');
a.forEach((current) => current.addEventListener('click', (e) => e.preventDefault()));
I also wonder whether the anchor tag is semantically appropriate for this purpose. I am open to alternative suggestions.
You can use preventDefault to prevent the default (redirect) behavior:
function handleClick(e) {
e.preventDefault()
// todo: do the onClick job
}
// ...
notes.forEach(note => <a href="#" onClick={handleClick}>{note.title}</a>);
// Also, i think you should add key={some_unique_key} in above anchor tags

How to setup React Router <Link> inside a Datatables.net Cell?

I have a datatables table (https://datatables.net) initialized like this:
$('#example').DataTable({
data: data,
columns: [{
title: "Database ID",
data: 'database_id',
render: function (data, type, row) {
return '<NavLink to="/shop">'+ data +'</NavLink>';
}
}]
});
The NavLink that i have in the code is supposed to render a database cell as a clickable link because of React-Router (This whole function is inside a React component), but the link is not rendering when i run the code.
What i ultimately want is the ability to click on a database cell that will take me to another component by routing into a link like "/shop/id" but i am stuck in it for a long time. Help!
I was facing the same issue and below solution is working for me.
You can directly add anchor tag with href to the path where you want to route upon on the click. But, it will reload your application.
To avoid reloading of the application, try below solution.
When you're initializing the columns dynamically, you can add below code for the column where you want to have a link.
fnCreatedCell: (nTd, data) => ReactDOM.render(
<a
onClick={() => handletableclick(data, props)}>
{data}
</a>, nTd)
Add handletableclick() function/method in your file to handle click event and programmatically through history push the path where you want to route upon the click
function handletableclick(data, props) {
props.history.push("/pathToRoute=" + data);
}
Also,in above code to access history from props, you will need to enclose your component with withRouter
like below :
export default withRouter(YourComponentName);

React router keep query params when changing route and back

I have a website with different pages based on react-router v4. Each page have url query based filters it means filter setting are stored on url like mysite.com/page1?filterKey=value.
My goal is to keep filter values on query when user back from another page ( mysite.com/page2).
The only 2 ways I see is either to use redux as Will Jenkins suggested, or to set the state in the parent container (either App.js, or the file handling your routes) :
In the parent container, define the function
setQuery = query => this.setState({query})
Pass the function to the child component
In the child component, pass the query on componentDidMount :
componentDidMount (){
this.setQuery( decodeURIComponent(querySearch(this.props.location.search).param) )
}
I found other one solutions using react hooks based global state:
const [podcastsUrlSearch, updateGlobalState] = useGlobalState('podcastsUrlSerach')
useLayoutEffect(() => {
if (!isEqual(props.location.search, podcastsUrlSearch)) {
updateGlobalState(props.location.search)
}
if (podcastsUrlSearch) {
props.history.replace({ ...props.history.location, search: podcastsUrlSearch })
}
}, [])
useLayoutEffect(() => {
updateGlobalState(props.location.search)
}, [props.location.search])
For example using a dropdown as a filter
use -->localStorage.setItem("companyDrpDwnValue")
on onChange event
and call the the below method to intialize the param on ComponentDidMount ,with which you were filtering the table
and filter the array with the filter param to get your filtered array

Navigate to a different route programmatically

I have a usecase where I have a list of elements inside some component similar to vanilla html select. I want, when user clicks on any of the element inside list, route should change. Can I use some regex while defining route and change route by using some API method from react router, onValueChange event of select?
Example
Root route: /
List Data: Cat, Dog, Elephant
When someone clicks on Cat I want him to get navigated to /Cat, similarly /Dog, /Elephant.
So after talking about it for a bit. figured out what you were wanting to do.
you need to define a new route in react-router that you can use for this history change.. something like this:
<Route exact path="/:name" component={SomeComponent} />
in your component you have access to this "name" via this.props.params.name
you can also call an action to update the store before updating this route
Note: if you stay with v2... You should make your actions return a promise, so that you can just chain the event in your component. aka:
onChange={this.handleChange}
handleChange = (value) => { // assuming you have the value here.. it may be e is the function param and you get the value as e.target.value
this.props.saveSelectedAnimal(value).then( () => {
this.props.history.push("/");
})
}

How to prevent route change using react-router

There's a certain page in my React app that I would like to prevent the user from leaving if the form is dirty.
In my react-routes, I am using the onLeave prop like this:
<Route path="dependent" component={DependentDetails} onLeave={checkForm}/>
And my onLeave is:
const checkForm = (nextState, replace, cb) => {
if (form.IsDirty) {
console.log('Leaving so soon?');
// I would like to stay on the same page somehow...
}
};
Is there a way to prevent the new route from firing and keep the user on the same page?
It is too late but according to the React Router Documentation you can use preventing transition with helping of <prompt> component.
<Prompt
when={isBlocking}
message={location =>
`Are you sure you want to go to ${location.pathname}`
}
/>
if isBlocking equal to true it shows a message. for more information you can read the documentation.
I think the recommended approach has changed since Lazarev's answer, since his linked example is no longer currently in the examples folder. Instead, I think you should follow this example by defining:
componentWillMount() {
this.props.router.setRouteLeaveHook(
this.props.route,
this.routerWillLeave
)
},
And then define routerWillLeave to be a function that returns a string which will appear in a confirmation alert.
UPDATE
The previous link is now outdated and unavailable. In newer versions of React Router it appears there is a new component Prompt that can be used to cancel/control navigation. See this example
react-router v6 no longer supports the Prompt component (they say that they hope to add it back once they have an acceptable implementation). However, react-router makes use of the history package which offers the following example for how to block transitions.
Note that to actually make this work in react router you have to replace the createBrowserHistory call with some hackery to make sure you are using the same history object as react router (see bottom of answer).
const history = createBrowserHistory();
let unblock = history.block((tx) => {
// Navigation was blocked! Let's show a confirmation dialog
// so the user can decide if they actually want to navigate
// away and discard changes they've made in the current page.
let url = tx.location.pathname;
if (window.confirm(`Are you sure you want to go to ${url}?`)) {
// Unblock the navigation.
unblock();
// Retry the transition.
tx.retry();
}
You'll need to put this inside the appropriate useEffect hook and build the rest of the functionality that would have otherwise been provided by prompt. Note that this will also produce an (uncustomizable) warning if the user tries to navigate away but closing the tab or refreshing the page indicating that unsaved work may not be saved.
Please read the linked page as there are some drawbacks to using this functionality. Specifically, it adds an event listener to the beforeunload event which makes the page ineligable for the bfcache in firefox (though the code attempts to deregister the handler if the navigation is cancelled I'm not sure this restores salvageable status) I presume it's these issues which caused react-router to disable the Prompt component.
WARING to access history in reactrouter 6 you need to follow something like the instructions here which is a bit of a hack. Initially, I assumed that you could just use createBrowserHistory to access the history object as that code is illustrated in the react router documentation but (a bit confusingly imo) it was intended only to illustrate the idea of what the history does.
We're using React Router V5, and our site needed a custom prompt message to show up, and this medium article helped me understand how that was possible
TLDR: the <Prompt/> component from react-router-dom can accept a function as the message prop, and if that function returns true you'll continue in the navigation, and if false the navigation will be blocked
React-router api provides a Transition object for such cases, you can create a hook in a willTransitionTo lifecycle method of the component, you are using. Something like (code taken from react-router examples on the github):
var Form = React.createClass({
mixins: [ Router.Navigation ],
statics: {
willTransitionFrom: function (transition, element) {
if (element.refs.userInput.getDOMNode().value !== '') {
if (!confirm('You have unsaved information, are you sure you want to leave this page?')) {
transition.abort();
}
}
}
},
handleSubmit: function (event) {
event.preventDefault();
this.refs.userInput.getDOMNode().value = '';
this.transitionTo('/');
},
render: function () {
return (
<div>
<form onSubmit={this.handleSubmit}>
<p>Click the dashboard link with text in the input.</p>
<input type="text" ref="userInput" defaultValue="ohai" />
<button type="submit">Go</button>
</form>
</div>
);
}
});

Resources