Next.js equivalent for useRouteMatch - javascript

I'm migrating a React app to Next.js.
Since Next.js doesn't use "react-router-dom", I need to change some of the React Router hooks so that they work with Next.js.
One of them is useRouteMatch.
I want to get this line of code to work with Next.js -
const match = useRouteMatch<{lang?: Language}>('/map/:lang([a-z]{2})?');
I haven't managed to find an equivalent method or workaround for this yet.
Does anyone have any suggestions?

Everything about nextjs route is in next/route.
You might be looking at router.pathname
const Component = () => {
const router = useRouter() //now u can use the router object
}
https://nextjs.org/docs/api-reference/next/router#router-object

Related

Unable to use router.push in Reactjs

I am working on Reactjs and using nextjs,Right now i am trying to refresh page (using routes) but i am getting following error
Error: No router instance found. you should only use "next/router" inside the client side of your app.
Here is my current code
const Post = ({ post, blogs }) => {
const routers = useRouter();
var spath=routers.asPath;
routers.push({ pathname: spath, query: '' });
})
You probably used router outside of a functional component or hook.
Convert Post to hook and it should work.
If you are running this code on application load or on any data change. You should do this inside useEffect hook because while rendering application on sever router won't be there and useEffect runs only inside browser.

Use nextjs routing outside react hooks in regular javascript

I have a NextJS app. I want to add a function that can redirect to any page using nextjs routing.
For example, after finishing signup I want to redirect to a certain page.
If I create this function (reusable everywhere) :
import { useRouter } from 'next/router'
const goTo = (href) => {
const router = useRouter()
router.push(href)
}
I want to add this to my signup Logic, the problem is that I break React Hooks rules :
react-dom.development.js?ac89:14906 Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
And effectively useRouter is a React Hook, and I'm trying to call it outside a React function, as stipulated here https://reactjs.org/docs/hooks-rules.html it will not work.
How can I then have a routing solution for NextJS to be callable in regular Javascript ?
So If you're using purely React.js (without Next.js on top of it), you can simple do it this way:
Import React from 'react'
export const handleRoutes = (url) => {
const history = React.useHistory()
return history.push(url)
}
Then You'd import this regular js function in any of your react files, like this:
import { handleRoutes } from 'fileName.js'
<button onClick={() => handleRoutes("/routeToBeRedirectedTo")}> Click to redirect </button>
However when using Nextjs I'm not sure that the above way would work. My personal method would be simply implementing this function (in a utility.js file):
export const handleRedirect = (router, url) => {
return router.push(url)}
Then just importing the function & useRouter hook in the file you want:
import { handleRedirect } from "./utility.js"
import { useRouter } from "next/router"
const router = useRouter
Then inside your JSX return statement:
<button onClick={() => handleRedirect(router, "/routeToBeRedirectedTo")}> Click to redirect </button>
And if it's a redirect after sign in/sign up, just simply useEffect like so:
// depends if you're storing your user credentials in your local storage or cookies, this example below would be if your User credentials are stored in localstorage
const user = JSON.parse(localstorage.getItem("user"))
UseEffect(() => {
if (user) return handleRedirect(router, "/routeToBeRedirectedTo")
}, [user])

How to properly use useHistory () from react-router-dom?

How to use useHistory() correctly? I can't make the transition from one react component to another.
According to the instructions from the React documentation and also here on Stack Overflow, I cannot make the transition from App.js to MyComponent.js.
For example - I am trying
/* **App.js ** */
/* Import modules */
import React from 'react';
import { useHistory } from 'react-router-dom'; // version 5.2.0
function App()
{
let history = useHistory ();
const handleClick = () => {
history.push ('./pages/MyComponent');
}
return (
<div className="App">
<button onClick={handleClick}>Next page ==></button>
</div>
);
}
I also tested this example, but the output throws the following error when the button is pressed:
TypeError: Cannot read property 'push' of undefined
Does something seem to be leaking to me or is there a mistake on Babel's side?
Project react structure:
+ Root/
+ src/
- App.js
- index.js
+ pages/
- MyComponent.js
This has changed in v6, useHistory is now useNavigate and we can use it as follows:
instead of:
const history = useHistory()
history.push('/')
we now use:
const navigate = useNavigate()
navigate('/')
You can't just use the useHistory hook to redirect to another page.
You need to properly set up your application in order to use React Router. Look at their examples starting from this https://reactrouter.com/web/example/basic
You need to wrap your entire application with <BrowserRouter /> which will give the history object you are looking for through the hook.
By the way, you don't give a relative file path to history.push as an argument, you must give a valid route that you typically setup using <Route /> component
Using history.replace('/<route-name>') also works.
you need to use it with react-router-dom. set your router config and then push it to that path. you can get more information by looking at documentation.
https://reactrouter.com/web/example/route-config
do not forget to set your switch components and your exact for root path.
Using React 17.0>, this works for me:
import { useHistory } from "react-router-dom";
const history = useHistory();
history.push("/home");
I've reached too much to find this correctly use of the useHistory function.
Try and answer this post for feedback.
When you are applying history.push, is that your path name? history.push('/pathname') is the process I guess.
You can see here: https://reactrouter.com/web/api/Hooks

Vue Composition API from outside of Vue

So, I've started using the Vue Composition API, and it's brilliant. I'm using it in a project that has Vue components, but also Vanilla JS. I'm building a notification system in Vue, as we are slowly moving everything that way.
I have the following code currently for adding a notification
export const useNotification = () => {
const notifications = ref([]);
const visibleNotifications = computed(() => {
return notifications.value.filter(notification => notification.visible === true).reverse();
});
const add = (notification: Notification) => {
notifications.value.push(notification);
};
};
I can get this adding perfectly from within Vue, but I want to also add a notification from the vanilla JS parts of the system. I've tried using useNotification().add() but I get the following error [vue-composition-api] must call Vue.use(plugin) before using any function. Basically, it wants me to use it inside Vue.
Any ideas on how I get this working?
Due to the shortcomings of using the vue-composition-api with vue2, and following the SO question here, I needed to add the following to type of my exported TS file
import Vue from 'vue';
import VueCompositionApi from '#vue/composition-api';
Vue.use(VueCompositionApi);

React v15.0.0: Since that renderToString is deprecated, how to go about server-side rendering?

There is a new release candidate of React, v 15.0.0. Since the renderToString method now is deprecated in the library, and apparently is going to be discontinued in future versions, what is the way to support server-side rendering with React in the new version?
On the docs page, no replacement for the renderToString or other explanation has been provided except that this particular method is no longer supported.
Thank you
As described in the comments, the correct (and only) way to render to a string with recent versions of React is to use ReactDOMServer's renderToString. Lots of existing answers and documentation refer to the removed React.renderToString, though. It has been deprecated for a while, but apparently only removed recently.
A quick and dirty example of what this might look like (running with node-babel):
const Express = require('express')
const React = require('react')
const ReactDomServer = require('react-dom/server')
const Label = React.createClass({
render: function () {
return <p> Foo! </p>
}
})
const server = Express()
server.use(function(req, res) {
const appHtml = ReactDomServer.renderToString(<Label />)
res.send(appHtml)
})
server.listen(3000)

Categories

Resources