React ScrollToTop component problem : it should work but it doesn't - reactjs

I am coding a React app and I'm trying to use a ScrollToTop component in order to scroll down in the app. But the problem is that for some reason it is not working at all.
Please help I'm really struggling with this one...
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default () => {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo({ top: 0, left: 0, behavior: "auto" });
}, [pathname]);
return null;
}
And I import this component in App.js
import React from 'react'
import { HashRouter } from "react-router-dom";
// import * as serviceWorker from './serviceWorker';
// core styles
import "./scss/volt.scss";
// vendor styles
import "#fortawesome/fontawesome-free/css/all.css";
import "react-datetime/css/react-datetime.css";
import HomePage from "./pages/HomePage";
import ScrollToTop from "./ScrollToTop";
function App() {
return (
<HashRouter>
<ScrollToTop/>
<HomePage />
</HashRouter>
)
}
export default App
Can anybody help me?

Please try with this.
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export default () => {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0,0);
}, [pathname]);
return null;
}

Related

how to use protected route in nextjs? i have multiple login page for different purpose

I have multiple login page and register page in nextjs app. I have checked the token in _app.js and component will not be render as the token will not be set. Token only get set after the form is submitted or login. how to fix this in nextjs.
import { React, useEffect, useState } from "react";
import "../styles/globals.css";
import "primereact/resources/themes/lara-light-indigo/theme.css"; //theme
import "primereact/resources/primereact.min.css"; //core css
import "primeicons/primeicons.css";
import "primeflex/primeflex.css";
import store from "../redux/store";
import { Provider } from "react-redux";
import "react-toastify/dist/ReactToastify.css";
// import "bootstrap/dist/css/bootstrap.min.css";
import "../styles/Nav.css";
import "../styles/temp.css";
import MainLayout from "../component/Layouts/MainLayout";
import { setAuthorizationToken } from "../redux/incomeTax/d03/action";
import IndexLayout from "../component/Layouts/IndexLayout";
import { useRouter } from 'next/router';
function MyApp({ Component, ...pageProps }) {
const { asPath, pathname } = useRouter();
// const router = useRouter();
console.log({asPath}); // '/blog/xyz'
console.log({pathname}); // '/blog/[slug]'
const [tokens, setTokens] = useState("");
useEffect(() => {
if(typeof window !== "undefined")
{
require("bootstrap/dist/css/bootstrap.min.css");
}
}, [])
useEffect(() => {
const token = localStorage.token1 ? localStorage.token1 : "";
console.log({token});
if (tokens !== token) {
setTokens(token);
setAuthorizationToken(token);
}
});
return (
<>
<Provider store={store}>
{ tokens !==''?
(
<MainLayout>
<Component {...pageProps} />
</MainLayout>
):
(
// RouteFunction()
<IndexLayout>
</IndexLayout>
)
}
</Provider>
</>
);
}
export default MyApp;
the above page is of _app.js which resides in pages folder.

matomo-tracker-react useMatomo returns "Invalid hook call"

im trying to implement matomo analytics within my react application (cra), however it trows an invalid hook call exception. Code has been copied from the simple example
https://www.npmjs.com/package/#datapunt/matomo-tracker-react
Did i miss something?
react: 17.0.2
react-dom: 17.0.2
code:
Index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Provider } from "react-redux";
import store from "./redux/store";
import { MatomoProvider, createInstance } from "#datapunt/matomo-tracker-react";
const matomo = createInstance({
urlBase: "http://192.168.133.226/",
siteId: 3,
heartBeat: {
active: true,
seconds: 10,
},
linkTracking: false,
configurations: {
disableCookies: true,
setSecureCookie: true,
setRequestMethod: "POST",
},
});
ReactDOM.render(
<MatomoProvider value={matomo}>
<Provider store={store}>
<App />
</Provider>
</MatomoProvider>,
document.getElementById("root")
);
App.js
import React, { useEffect } from "react";
import "./App.scss";
import { BrowserRouter as Router, Link } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { useMatomo } from "#datapunt/matomo-tracker-react";
import Navigation from "./components/navigation/navigation";
import Sitemap from "./components/sitemap/sitemap";
import Main from "./pages/main/main";
function App() {
const modal = useSelector((state) => state.modal);
const items = useSelector((state) => state.items);
const app = useSelector((state) => state.app);
const dispatch = useDispatch();
const { trackPageView } = useMatomo();
useEffect(() => {
trackPageView();
// eslint-disable-next-line
}, []);
return (
<div className='app'>
<Router>
<Navigation />
<Sitemap />
<Main />
</Router>
</div>
);
}
export default App;
You need to create the Matamo instance first and then wrap everything around that.
Refer this https://www.npmjs.com/package/#datapunt/matomo-tracker-react
https://github.com/jonkoops/matomo-tracker/tree/main/packages/react
Use this one & try again:
npm install #jonkoops/matomo-tracker-react
import { MatomoProvider, createInstance } from '#jonkoops/matomo-tracker-react'
import { useMatomo } from '#jonkoops/matomo-tracker-react'

Getting "TypeError: render is not a function" error when i import context from another file

I am trying to do react context on a function. Initially, I created react context in the same file as the provider, but then I got a warning on the console saying that I should put context in a separate file, but when I do that, for some bizarre reason, I get an error, even though I am pretty much doing the exact same thing, what am I doing wrong? I am only showing the relevant bits of the code.
The following code below works fine
import * as React from 'react';
import {
BrowserRouter as Router,
NavLink,
Switch,
Route,
} from 'react-router-dom';
import Header from './header.js';
import './OldApp.css';
import { useState, useEffect } from 'react';
//Context import commented
//import UserObjAndDbProvider from './dbAndUserObjContext';
import routes from './routes';
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
const Context = React.createContext();
export const UserObjAndDbProvider = Context.Provider;
export const UserObjAndDbConsumer = Context.Consumer;
const App = ({ user, database }) => {
var [membership, setMembership] = useState(false);
const docRef = database.collection("userCollection").doc(`${user.uid}`)
//get data
const FindOutMembership = async () => {
var booleanVal = null;
docRef.get().then(function(doc) {
if (doc.exists) {
const booleanVal = doc.data().membership;
setMembership(membership = booleanVal);
} else {
console.log("Error: no such document exists")
}
})
}
useEffect(() => {
FindOutMembership();
})
return (
<UserObjAndDbProvider value={'i am sexy and i like it'}>
<Router>
//some routing stuff done here
</Router>
</UserObjAndDbProvider>
);
};
export default App;
but when i take context stuff out, and put in in another file(which is in the same folder) and import it i get a weird error titled "TypeError: render is not a function"
import * as React from 'react';
import {
BrowserRouter as Router,
NavLink,
Switch,
Route,
} from 'react-router-dom';
import Header from './header.js';
import './OldApp.css';
import { useState, useEffect } from 'react';
//Context import now uncomment
import UserObjAndDbProvider from './dbAndUserObjContext';
import routes from './routes';
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
import { useContext, createContext } from 'react';
const App = ({ user, database }) => {
var [membership, setMembership] = useState(false);
const docRef = database.collection("userCollection").doc(`${user.uid}`)
const FindOutMembership = async () => {
var booleanVal = null;
docRef.get().then(function(doc) {
if (doc.exists) {
const booleanVal = doc.data().membership;
setMembership(membership = booleanVal);
} else {
console.log("Error: no such document exists")
}
})
}
useEffect(() => {
FindOutMembership();
})
//console.log(membership);
return (
<UserObjAndDbProvider value={'i am sexy and i like it'}>
<Router>
//some routing stuff done here
</Router>
</UserObjAndDbProvider>
);
};
export default App;
my context file is called dbAndUserObjContext.js and looks like this
import React from 'react'
import { createContext } from 'react';
const Context = React.createContext();
export const UserObjAndDbProvider = Context.Provider;
export const UserObjAndDbConsumer = Context.Consumer;
export default Context;

React Native useState

When I tried to use useState I get this error:
Component Exception
(0,_reactNative.useState) is not a function.(In'(0,_reactNative.useState)(false)','(0,reactNative.useState)' is undefined)
Source
var children = Component(props, secondArg);
Please help me. I dont understand why I cannot use useState:(
Here is my code:
`
import React from 'react';
import {StyleSheet,View,Text, Modal,useState} from 'react-native';
import { createAppContainer,NavigationContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import HomeScreen from './android/screens/HomeScreen/index';
import LoginScreen from './android/screens/Login/index'
const AppNavigator = createStackNavigator(
{
Home: {screen: HomeScreen},
Login: {screen: LoginScreen},
},
{
initialRouteName:'Login'
}
);
const AppContainer= createAppContainer(AppNavigator);
export default function App () {
const [modalVisible, setModalVisible] = useState(false);
return (
<AppContainer/>
)
}
As pointed out by Nicholas, import useState from react and not from react-native,
import React, {useState} from 'react';
import {StyleSheet,View,Text, Modal} from 'react-native';

Merging two objects with useContext and state?

So i have this problem where it doesn't merge the two objects since refsContext is empty when useEffect gets called after render. It ends with only one of the refs in the object. useEffect(() => {setRef(something)}, [ref]); results in an infinite empty object loop. Did i miss something?
refs.context.jsx
import { createContext } from "react";
const refsContext = createContext({});
export default refsContext;
Same code over multiple files
/** #jsx jsx */
import React, { useContext, useEffect, useRef } from "react";
import refsContext from "../../context/refs.context";
const StackoverflowExample= () => {
const projectsRef = useRef(null);
const [ref, setRef] = useContext(refsContext);
useEffect(() => {
setRef({ ...ref, projects: projectsRef.current });
}, []);
return (
<section ref={projectsRef}></section>
);
};
export default StackoverflowExample;
App.jsx
import React, { useState, useEffect } from "react";
import { render } from "react-dom";
import Pages from "./Pages";
import { BrowserRouter } from "react-router-dom";
import refsContext from "./context/refs.context";
const App = () => {
//Default Contexts
const refsHook = useState({});
console.log(refsHook[0]);
//All my wrappers/providers for my App
return (
<refsContext.Provider value={refsHook}>
<BrowserRouter>
<Pages/>
</BrowserRouter>
</refsContext.Provider>
);
};
render(<App />, document.getElementById("root"));

Resources