I expect that console.log('Refresh') runs every time the route changes (switching from Component1 to Component2). But it's only triggering on first render. Why?
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('root'));
App.js:
import React, { useEffect } from 'react';
import { Switch, Route } from 'react-router-dom';
import Nav from './Nav';
import Component1 from './Component1';
import Component2 from './Component2';
const App = () => {
useEffect( () => console.log('Refresh'));
return (
[<Switch>
<Route component = {Nav}/>
</Switch>,
<Switch>
<Route exact path = '/component1' component = {Component1}/>
<Route exact path = '/component2' component = {Component2}/>
</Switch>]
);
}
export default App;
Nav.js:
import React from 'react';
import { Link } from 'react-router-dom';
const Nav = () => {
return (
<div>
<Link to = '/component1'>Component 1</Link>
<Link to = '/component2'>Component 2</Link>
</div>
);
}
export default Nav;
Component1.js:
import React from 'react';
const Component1 = () => {
return (
<div>
<p>Hi</p>
</div>
);
}
export default Component1;
Component2.js:
import React from 'react';
const Component2 = () => {
return (
<div>
<p>Bye</p>
</div>
);
}
export default Component2;
The useEffect is not triggered because the App component is not re-rendered, nothing changed in that component (no state or props update).
If you want the App component to re-render when the route change, you can use the withRouter HOC to inject route props, like this :
import { Switch, Route, withRouter } from 'react-router-dom';
const App = () => {
useEffect( () => console.log('Refresh'));
return (...);
}
export default withRouter(App);
Example : https://codesandbox.io/s/youthful-pare-n8p1y
use the key attribute so everytime we render new component (different key)
<Route path='/mypath/:username' exact render= {routeProps =><MyCompo {...routeProps} key={document.location.href} />} />
Use the 2nd argument to useEffect to conditionally apply effect. For example via react-router-dom, you get some properties
const { schoolId, classId } = props
useEffect(() => {
// fetch something here
}, [schoolId, classId)
Here [schoolId, classId acts as the unique identifier for useEffect to trigger.
Using Hooks:
use useLocation and useLayoutEffect get more efficiency:
import { useLocation } from "react-router-dom";
//...
const location = useLocation();
//...
useLayoutEffect(() => {
console.log("location",location)
}, [location])
Related
Here is an Error:
Objects are not valid as a React child (found: object with keys {$$typeof, type, compare, WrappedComponent}). If you meant to render a collection of children, use an array instead.
It works just fine if I don't use connect in main.js and using connect in App.js doesn't make an Error, but once I use connect in main.js it throws me this error. What do I do wrong? And I'm using connect same way as in App.js Thank you
Here is sandBox https://codesandbox.io/s/busy-euler-7mpi7?file=/src/main.js
you can experience, just delete connect in main.js and it will start working
App.js
import React, { useEffect } from "react";
import './styles/main.scss';
import './App.scss';
import routes from "./router/router";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { connect } from "react-redux";
import {checkUser, fetchUsers, fetchPolls} from "./store/index";
function App (props) {
useEffect(() => {
let { loadUsers} = props
loadUsers();
}, [])
let jsxRoutes = routes.map(el =>
<Route
path={el.url}
exact={el.exact}
key={el.url}>
{ el.component }
</Route>
)
return (
<Router>
<div className="App">
<Switch>
{ jsxRoutes }
</Switch>
</div>
</Router>
);
}
const mapStateToProps = state => {
return {
users: state.users.data,
}
}
const mapDispatchToProps = dispatch => {
return {
loadUsers: () => dispatch(fetchUsers())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
Main.js
import React from "react";
import "./main.scss"
import { connect } from "react-redux"
const Main = (props) => {
return(
<main>
main pg
</main>
)
}
export default connect(null, null)(Main);
In App.js try this instead:
let jsxRoutes = routes.map((el) => (
<Route path={el.url} exact={el.exact} key={el.url} component={el.component} />
));
Or the shorter version: <Route {...el} />
In my react app, I am using the useHistory hook to redirect to my Home Component. Why is useHistory undefined, and how would I solve this problem?
App.js
import 'bootstrap/dist/css/bootstrap.css'
import React from "react";
import { Button } from 'react-bootstrap';
import { BrowserRouter, Route, useHistory} from 'react-router-dom';
import { Switch } from 'react-router-dom/cjs/react-router-dom.min';
import './App.css';
import Home from './components/Home/Home';
const App = () =>
{
const history = useHistory()
const handleClick = () =>
{
console.log(history)
console.log("handle click")
// history.push("/home") this line throws "cannot read property of undefined" error
}
return (
<>
<BrowserRouter>
<Button onClick = {handleClick} variant = "primary">Get Started</Button>
<Switch>
<Route path="/home" exact component = {Home}/>
</Switch>
</BrowserRouter>
</>
);
}
export default App;
Try to use the useHistory() outside this component and see it work. It seems you are calling the function before the Router itself and both are imported from react-router-dom .
I have a simple react hooks application - a list of Todos - with react router v4
On the List of Todos, when a Todo is clicked I need to:
Dispatch the current todo in context
Redirect to another route (from /todos to /todos/:id)
In the previous React Class based implementation I could use this.context.history.push to redirect to another route.
How would I handle that using React Hooks in combination of React Router v4 (in code below see my comment in function editRow())?
Code below:
=====index.js=====
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter} from "react-router-dom"
import App from './App';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>, document.getElementById('root'));
=====main.js=====
import React from 'react'
import { Switch, Route } from 'react-router-dom'
import TodosList from './todoslist'
import TodosEdit from './todosedit'
const Main = () => (
<main>
<Switch>
<Route exact path="/todos" component={TodosList}/>
<Route exact path="/todos/:id" component={TodosEdit} />
</Switch>
</main>
)
export default Main
=====app.js=====
import React, {useContext, useReducer} from 'react';
import Main from './main'
import TodosContext from './context'
import todosReducer from './reducer'
const App = () => {
const initialState = useContext(TodosContext);
const [state, dispatch] = useReducer(todosReducer, initialState);
return (
<div>
<TodosContext.Provider value={{state, dispatch}}>
<Main/>
</TodosContext.Provider>
</div>
)
}
export default App;
=====TodosContext.js=====
import React from 'react'
const TodosContext = React.createContext({
todos: [
{id:1, text:'Get Grocery', complete:false},
{id:2, text:'Excercise', complete:false},
{id:3, text:'Drink Water', complete:true},
],
currentTodo: {}
})
export default TodosContext
=====reducer.js=====
import React from 'react'
export default function reducer(state, action){
switch(action.type){
case "GET_TODOS":
return {
...state,
todos: action.payload
}
case "SET_CURRENT_TODO":
return {
...state,
currentTodo: action.payload
}
default:
return state
}
}
=====Todos.js=====
import React, {useState, useContext, useEffect} from 'react';
import TodosContext from './context'
function Todos(){
const [todo, setTodo] = useState("")
const {state, dispatch} = useContext(TodosContext)
useEffect(()=>{
if(state.currentTodo.text){
setTodo(state.currentTodo.text)
} else {
setTodo("")
}
dispatch({
type: "GET_TODOS",
payload: state.todos
})
}, [state.currentTodo.id])
const editRow = event =>{
let destUrlEdit = `/todos/${event.id}`
let obj = {}
obj.id = event.id
obj.text = event.text
dispatch({type:"SET_CURRENT_TODO", payload: obj})
//after dispatch I would like to redirect to another route to do the actual edit
//destUrlEdit
}
return(
<div>
<h1>List of ToDos</h1>
<h4>{title}</h4>
<ul>
{state.todos.map(todo => (
<li key={todo.id}>{todo.text}
<button onClick={()=>{
editRow(todo)}}>
</button>
</li>
))}
</ul>
</div>
)
}
export default Todos;
It's actually a lot simpler than the other answers, React Router v5.1 provides a useHistory hook.
import React from 'react'
import { useHistory } from 'react-router-dom'
const MyComponent = () => {
const history = useHistory()
const handleButtonClick = (event) => {
history.push(event.target.value)
}
return (
<button
type="button"
value="/my/path"
onClick={handleButtonClick}
>
Navigate Me!
</button>
)
}
Your problem is related to Programmatically navigating using react-router-v4 instead of with hooks,
In react-router-v4, you would get history from props if the Todos component is rendered as a child or Route or from an ancestor that is render form Route and it passed the Router props to it. However it is not receiving Router props, you can use withRouter HOC from react-router to get the router props and call props.history.push(destUrlEdit)
import React, {useState, useContext, useEffect} from 'react';
import TodosContext from './context'
import { withRouter } from 'react-router-dom';
function Todos(props){
const [todo, setTodo] = useState("")
const {state, dispatch} = useContext(TodosContext)
useEffect(()=>{
if(state.currentTodo.text){
setTodo(state.currentTodo.text)
} else {
setTodo("")
}
dispatch({
type: "GET_TODOS",
payload: state.todos
})
}, [state.currentTodo.id])
const editRow = event =>{
let destUrlEdit = `/todos/${event.id}`
let obj = {}
obj.id = event.id
obj.text = event.text
dispatch({type:"SET_CURRENT_TODO", payload: obj})
//after dispatch I would like to redirect to another route to do the actual edit
//destUrlEdit
props.history.push(destUrlEdit);
}
return(
<div>
<h1>List of ToDos</h1>
<h4>{title}</h4>
<ul>
{state.todos.map(todo => (
<li key={todo.id}>{todo.text}
<button onClick={()=>{
editRow(todo)}}>
</button>
</li>
))}
</ul>
</div>
)
}
export default withRouter(Todos);
You can use UseNavigate to move the change page. here is the sample example
"react-router-dom": "^6.2.1",
// Route File
import React, { Suspense, lazy } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import IndexLayout from "../layouts";
import NotFoundPage from "../views/404";
import Loader from "../components/Loader";
const Dashboard = lazy(() => import("../containers/DashboardContainer"));
const Router = () => {
return (
<BrowserRouter>
<IndexLayout> // this one is kind of HOC
<Routes>
<Route
path="/"
element={
<Suspense fallback={<Loader />}>
<Dashboard />
</Suspense>
}
/>
</end every thing>
// any component
import React, { useEffect } from "react";
import { useNavigate } from "react-router-dom";
const TestComponent = ({ newSignup }) => {
const navigate = useNavigate();
useEffect(() => {
if (newSignup) {
navigate("/login");
}
}, [newSignup]);
return (
<div>
</div>
)
}
export default TestComponent
Using react-redux and connected-react-router...
import {useDispatch } from 'react-redux';
import { push } from 'connected-react-router';
export default () => {
const dispatch = useDispatch();
return (
<Button onClick={() => dispatch(push('/login'))}>
Login
</Button>
);
};
I have reactjs setup with routes but my routing is not working. When I load the page it works but when I click on the links the URL changes but the component does not render. I tried to put as much as I can in the sandbox. load with URL/admin and click on logout etc.
https://codesandbox.io/s/o5430k7p4z
index
import React, { Component } from 'react'
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { BrowserRouter, Route, browserHistory } from 'react-router-dom';
import promise from 'redux-promise';
import { createLogger } from 'redux-logger';
import App from './App'
import reducers from './reducers';
require("babel-core/register");
require("babel-polyfill");
import 'react-quill/dist/quill.snow.css'; // ES6
const logger = createLogger();
const initialState = {};
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<App/>
</BrowserRouter>
</Provider>
, document.getElementById('root'));
App
import React, { Component } from 'react'
import { Switch, Route } from 'react-router-dom';
import ReactGA from 'react-ga';
ReactGA.initialize('UA-101927425-1');
import { connect } from 'react-redux';
import { fetchActiveUser } from './actions/index';
import { bindActionCreators } from 'redux';
import {getHttpRequestJSON} from './components/HTTP.js'
import Header from './components/header';
import Logout from './components/logout';
import SideBar from './components/sidebar';
import HomeContent from './containers/home';
import Ldapuser from './components/ldapuser';
import Admin from './components/admin/admin';
function fireTracking() {
ReactGA.pageview(window.location.pathname + window.location.search);
}
class App extends Component {
constructor(props){
super(props);
this.state = {
isGuest : false,
isSupp : false,
loading: true,
version: '',
};
}
initData = () => {
let self = this;
getHttpRequestJSON('/api/user/get/user/method/is/guest/format/json?quiet=1')
.then((response) => {
let isGuest = response.body.recordset.record.isGuest;
if(isGuest){
/*$(".logo").trigger('click');
//$("#overlay").show();
$('#modalIntro').modal('toggle');
$("#modalIntro").on("hidden.bs.modal", function () {
$(".logo").trigger('click');
});*/
}
self.props.isGuest = isGuest;
self.props.loading = false;
//self.props.version = response.header.version;
self.setState({
loading : false,
version : response.header.version,
isGuest : isGuest
});
})
.catch(error => {
console.log("Failed!", error);
//$('#myModalError .modal-body').html(error);
//$('#myModalError').modal('show');
});
getHttpRequestJSON('/api/user/get/user/method/is/supp/format/json?quiet=1')
.then((response) => {
self.setState({
isSupp : response.body.recordset.record.isSupp
});
})
.catch(error => {
console.log("Failed!", error);
//$('#myModalError .modal-body').html(error);
//$('#myModalError').modal('show');
});
}
componentDidMount() {
this.props.fetchActiveUser();
this.initData();
}
render() {
return (
<div>
<Header activeUser={this.props.activeUser} loading={this.state.loading} version={this.state.version} title={`Home`} />
<SideBar />
<main>
<Switch>
<Route path='/index.html' render={()=><HomeContent activeUser={this.props.activeUser} isGuest={this.state.isGuest} isSupp={this.state.isSupp} />} />
<Route path='/home' render={()=><HomeContent activeUser={this.props.activeUser} isGuest={this.state.isGuest} isSupp={this.state.isSupp} />} />
<Route path='/logout' component={Logout}/>
<Route path='/ldapuser' component={Ldapuser}/>
<Route path='/admin' render={()=><Admin isGuest={this.state.isGuest} isSupp={this.state.isSupp}/>} />
</Switch>
</main>
</div>
);
}
}
//export default App;
function mapStateToProps(state) {
if(state.activeUser.id > 0){
ReactGA.set({ userId: state.activeUser.id });
}
// Whatever is returned will show up as props
// inside of the component
return {
activeUser: state.activeUser
};
}
// Anything returned from this function will end up as props
// on this container
function mapDispatchToProps(dispatch){
// Whenever getUser is called, the result should be passed
// to all our reducers
return bindActionCreators({ fetchActiveUser }, dispatch);
}
//Promote component to a container - it needs to know
//about this new dispatch method, fetchActiveUser. Make it available
//as a prop
export default connect(mapStateToProps, mapDispatchToProps)(App);
The codesandbox is not working, but I think what is happening to you is a very common problem when using react-redux and react-router. The connect HOC of react-redux has a builtin SCU (shouldComponentUpdate), so for it to know to rerender is requires to receive new props. This can be done using the withRouter hoc of react-router. Simply wrap connect(..)(MyComponent) with withRouter(connect(..)(MyComponent)) or do it clean and use compose (from recomponse for example);
const enhance = compose(
withRouter,
connect(mapStateToProps)
)
export default enhance(MyComponent)
Make sure not to do it the other way around, because that does not work.
I'm using react-router v4.2.2 in my project, and am trying to create a set of cards that each link to other components. Right now I'm just testing that the router works, by routing each Card to one specific component called 'Project1'. This, however, is not working; I'm not seeing the div inside the Project1 component pop up. What am I doing wrong?? Shouldn't each Card link to the Project1 component?
Here is the code for the main container that holds the cards:
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import ProjectCard from '../components/project_card.js';
import Project1 from '../components/project1.js';
class ProjectCards extends React.Component {
render() {
var projectCards = this.props.projects.map((project, i) => {
return (
<div key={i}>
<Link to={`/${project.title}`}>
<ProjectCard title={project.title} date={project.date} focus={project.focus}/>
</Link>
</div>
);
});
return (
<div>{projectCards}</div>
);
}
}
function mapStateToProps(state) {
return {
projects: state.projects
};
}
export default connect(mapStateToProps)(ProjectCards);
Here is the code for the Routes container:
import React from 'react';
import Project1 from '../components/project1.js';
import { connect } from 'react-redux';
import { Route, Switch } from 'react-router-dom';
class Routes extends React.Component{
render() {
var createRoutes = this.props.projects.map((project, i) => {
return <Route key={i} exact path={`/${project.title}`} component={Project1}/>
});
return (
<Switch>
{createRoutes}
</Switch>
);
}
}
function mapStateToProps(state) {
return {
projects: state.projects
};
}
export default connect(mapStateToProps)(Routes);
Here is the code for the index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyMiddleware, createStore } from 'redux';
import ReduxPromise from 'redux-promise';
import { BrowserRouter } from 'react-router-dom';
import App from './components/App.jsx';
import css from '../style/style.css';
import style from '../style/style.css';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
, document.getElementById('root'));
and the code for Project1, which should display when a Card has been clicked:
import React from 'react';
const Project1 = () => {
return (
<div>hello there this is Project1</div>
);
}
export default Project1;
When you click on a link, you navigate to Project1, which has no Routes defined. You basically destroy your Route when you lick on it because the Switch is in the same component as the Link. The Switch statement needs to be moved to a 3rd component so that it still exists after clicking on a linking card.