I have encountered a problem with th fact that reactDOM.render doesnt render the app despite yarn run compiling sucessfully.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from 'react-redux';
import {PersistGate} from 'redux-persist/integration/react';
import {store ,persistor} from './redux/store.js'
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<PersistGate persistor={persistor}>
<App />
</PersistGate>
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
Redux configuration in store.js
import { createStore, applyMiddleware } from 'redux';
import logger from 'redux-logger';
import {persistStore} from 'redux-persist';
import createSagaMiddleware from 'redux-saga';
import { fetchGalleryStart } from './gallery/gallery.saga';
import {rootReducer} from './root.reducer.js';
const sagaMiddleware= createSagaMiddleware();
const middlewares = [sagaMiddleware];
if (process.env.NODE_ENV==='development') {
middlewares.push(logger)
}
export const store = createStore(rootReducer, applyMiddleware(...middlewares));
export const persistor = persistStore(store);
sagaMiddleware.run(fetchGalleryStart); //inside run we pass each individual saga
const exportedObject = {
store,
persistor,
};
export default exportedObject;
The app.js
import React from 'react';
import { BrowserRouter, Switch, Route } from "react-router-dom";
import Header from './components/header/header.component.jsx';
import Footer from './components/footer/footer.component.jsx';
import HomePage from './pages/homepage/homepage.component.jsx';
import Contact from './pages/contact/contact.component.jsx';
import About from './pages/about/about.component.jsx';
class App extends React.Component {
render () {
return (
<div className="App">
<BrowserRouter>
<Header />
<div className="wrapper">
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/contact" component={Contact} />
<Route path="/about" component={About} />
<Route path="*">error</Route>
</Switch>
</div>
<Footer/>
</BrowserRouter>
</div>
);
}
};
export default App
When I open the app in the browser, the app is not rendered on the root, page stays blank.
Could you please help me where to look? I am pretty lost how to approach this since i receive no error.
Thank you for your time
Wrap your render()... method with a class component like this:
class App extends React.Component {
render() {
return ();
}
}
export default App;
To declare App correct.
Or get rid of render() method and do a function:
funciton App() => {
return (<div></div>);
}
export default App;
Hope I could help you and have fun!
Related
In my react application, I created store.js and rootreducer.js for it. Before creating the store.js and rootreducer.js file, my react application was working properly but after adding it, I'm actually not getting any error but my output on the local host is blank now. For including the store and reducer in my application I have imported the provider and store to my app.js file. If I remove them, my react application works properly but with these imports, I get a blank screen in my localhost. Below given is my store.js file
import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from './Reducer/rootReducer';
const initialState = {}
const middleWare = [thunk]
let store;
if (window.navigator.userAgent.includes("Chrome")) {
store = createStore(rootReducer,
initialState,
compose(applyMiddleware(...middleWare),
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__()
))
} else {
store = createStore(rootReducer,
initialState,
compose(applyMiddleware(...middleWare)))
}
export default store;
And this is my app.js file
import React from 'react';
import './App.css';
import Nav from './Component/Common/Nav';
import 'bootstrap/dist/css/bootstrap.css';
import Welcome from './Component/Welcome';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Dashboard from './Component/Dashboard/Dashboard';
import CreateMonthWallet from './Component/Dashboard/DashboardOperations/CreateMonthWallet';
import NotFound from './Component/Common/NotFound';
import { Provider } from 'react-redux';
import store from './Store';
//import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
function App() {
return (
<Provider store={store}>
<Router>
<div>
<Nav />
<Routes>
<Route path="/" element={<Welcome />} exact />
<Route path="/Dashboard" element={<Dashboard />} exact />
<Route path="/CreateMonthWallet" element={<CreateMonthWallet />} exact />
<Route path="*" element={<NotFound />} exact />
</Routes>
</div>
</Router>
</Provider>
);
}
export default App;
And this is my rootreducer.js file
import {combineReducers} from 'redux'
export default combineReducers({
});
you can add your store like this in app.js
your code
import store from './Store';
add this
import {store} from './Store';
hope this will help you!
I can't use connect, with export in App component. No error is thrown, the app starts normally... but all my links in my navbar stop to work (???). The url changes, but the main page is always displayed, like it would break the routing. Here is my code:
import { Route, Switch, Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import Layout from './hoc/Layout/Layout';
import BurgerBuilder from './containers/BurgerBuilder/BurgerBuilder';
import Checkout from './containers/Checkout/Checkout';
import Orders from './containers/Orders/Orders';
import Auth from './containers/Auth/Auth';
import * as actions from './store/actions'
class App extends Component {
render () {
return (
<div>
<Layout>
<Switch>
<Route path="/checkout" component={Checkout} />
<Route path="/orders" component={Orders} />
<Route path="/auth" component={Auth} />
<Route path="/" exact component={BurgerBuilder} />
</Switch>
</Layout>
</div>
);
}
}
const mapDispatchToProps = dispatch => {
return {
anything: ()=>dispatch(actions.logout())
}
};
export default connect(null, mapDispatchToProps)(App);
//export default App;
If I comment the 'connect' part, like this:
//export default connect(null, mapDispatchToProps)(App);
export default App;
everything runs ok and all my links are working fine. Why can't I use 'connect' in my App component? I know I'm not dispatching any actions through props, but it should work nontheless, as far as I'm concerned.
Below is my index.js file, which uses th App component:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import burgerBuilderReducer from './store/reducers/burgerBuilder';
import orderReducer from './store/reducers/order';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const rootReducer = combineReducers({
burgerBuilder: burgerBuilderReducer,
order: orderReducer
});
const store = createStore(rootReducer, composeEnhancers(
applyMiddleware(thunk)
));
const app = (
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
);
ReactDOM.render( app, document.getElementById( 'root' ) );
registerServiceWorker();
I think the problem is your mapDispatchToProps:
import {bindActionCreators} from 'redux'
...
const mapDispatchToProps = dispatch => (bindActionCreators({
actionName: () => ({type:'SOME_ACTION', payload: 'SOME_PAYLOAD'}),
doLogout: () => actions.logout(),
}, dispatch))
EDIT: Do this changes to your App.js
<BrowserRouter>
<Switch>
<Route path="/checkout" component={Checkout} />
<Route path="/orders" component={Orders} />
<Route path="/auth" component={Auth} />
<Route path="/" exact component={BurgerBuilder} />
</Switch>
</BrowserRouter>
I think I got it. The solution was to wrap both my App and Layout components (layout holds my navigation items) with "withRouter":
export default withRouter(connect(null, mapDispatchToProps)(App));
export default withRouter(connect(mapStateToProps)(Layout));
I created my application with create react app and the routes were working just fine up until a certain point the routes in my navbar I have as links would not load.
Been trying to debug for a while and was wondering if I could get some help as I feel like issue is coming from this specific file
import React from 'react'
import {fetchThreadds} from '../actions/fetchThreadds'
import Threaddform from '../components/Threaddform'
import Threaddlist from '../components/Threaddlist'
import Threaddshow from '../components/Threaddshow'
import {connect} from 'react-redux';
import {Route, Switch} from 'react-router-dom'
import { withRouter } from 'react-router-dom'
class ThreaddsContainer extends React.Component {
componentDidMount(){
this.props.fetchThreadds()
console.log("component did mount console", this.props)
}
render(){
console.log("render")
return(
<div>
<Switch>
<Route exact path='/thread/new' component={Threaddform}/>
{/* <Threaddform/><br></br> */}
<Route path='/threads/:id' render={(routerProps) => <Threaddshow {...routerProps} threadds={this.props.threadds}/>}/>
<Route exact path='/threads'render={()=> <Threaddlist threadds={this.props.threadds}/>} />
{/* <Threaddlist threadds={this.props.threadds}/> */}
</Switch>
</div>
)
}
}
const mapStateToProps = state => {
console.log("getting stuff from the store")
return {
threadds: state.threadds
}
}
export default withRouter(connect(mapStateToProps, {fetchThreadds}(ThreaddsContainer));
Will show all the necessary files below :
import React from 'react';
import './App.css';
import {connect} from 'react-redux';
import ThreaddsContainer from './containers/ThreaddsContainer';
class App extends React.Component {
render(){
return (
<div className="App">
<br></br> <h1 >The Sport Thread </h1>
<ThreaddsContainer/>
</div>
);
}
}
export default connect() (App);
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {createStore, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk';
import {Provider} from 'react-redux'
import threaddReducer from './reducers/threaddReducer'
import {BrowserRouter as Router, Route} from 'react-router-dom'
import Home from './components/Home'
import About from './components/About'
import Navbar from './components/Navbar'
import Sportupdate from './components/Sportupdate'
import Help from './components/Help'
import Login from './components/Login'
import Signup from './components/Signup'
import 'bootstrap/dist/css/bootstrap.min.css';
// import * as serviceWorker from './serviceWorker';
//The store
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
let store = createStore(threaddReducer, composeEnhancers(applyMiddleware(thunk)))
ReactDOM.render(
<Provider store={store}>
<Router>
<div>
<center><Navbar /></center>
<App />
<Route exact path="/" component={Home} />
<Route exact path="/about" component={About} />
<Route exact path="/updates" component={Sportupdate} />
<Route exact path="/help" component={Help} />
<Route exact path="/login" component={Login} />
<Route exact path="/signup" component={Signup} />
</div>
</Router>
</Provider>
,
document.getElementById('root')
);
and I am currently on react router v5!
Do let me know if I need to add more information
Use connected-react-router like below.
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App/App";
import { Provider } from "react-redux";
import * as serviceWorker from "./serviceWorker";
import { ConnectedRouter } from "connected-react-router";
import * as initFastClick from "react-fastclick";
import { HelmetProvider } from "react-helmet-async";
import { configureStore, history, injectGlobalSaga } from "./utils";
import LocaleProvider from "./_components/LocaleProvider/Loadable";
import AuthProvider from "./_components/AuthProvider/Loadable";
import { locales } from "./locale";
import "bootstrap/dist/css/bootstrap.min.css";
import "./custom.scss";
import * as GLOBAL_CONSTANTS from "./utils/constants";
initFastClick();
const initialState = {};
const store = configureStore(initialState, history);
injectGlobalSaga(store);
const render = () => {
ReactDOM.render(
<Provider store={store}>
<LocaleProvider messages={locales}>
<ConnectedRouter history={history}>
<HelmetProvider>
<AuthProvider>
<App />
</AuthProvider>
</HelmetProvider>
</ConnectedRouter>
</LocaleProvider>
</Provider>,
document.getElementById("root")
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
}
render();
serviceWorker.unregister();
I'm trying to connect react router v4 with redux but it's not working. I'm using withRouter as described in the docs, but props aren't available in my route components. Any idea?
Here's my code:
index.js
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import { routerMiddleware } from 'react-router-redux';
import { createLogger } from 'redux-logger';
import thunk from 'redux-thunk';
import createHistory from 'history/createBrowserHistory';
const history = createHistory();
const logger = createLogger();
const middleware = [
thunk,
routerMiddleware(history)
];
if (process.env.NODE_ENV === 'development') {
middleware.push(logger);
}
// create store
const store = createStore(
reducers,
applyMiddleware(...middleware)
);
render(
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>,
document.getElementById('root')
);
App.js
import React, { Component } from 'react';
import { Switch, Route, Link, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
class App extends Component {
componentDidMount() {
this.props.fetchPages(API_PAGES);
this.props.fetchPosts(API_POSTS);
}
render() {
return (
!this.props.pages.isFetching ?
<div>
<ul>
{this.props.pages.data && this.props.pages.data.map(page => (
<li key={page.id}>
<Link to={page.slug}>{page.title.rendered}</Link>
</li>
))}
</ul>
<Switch location={this.props.location}>
<Route path={routes.HOME} exact component={Home} />
<Route path={routes.ABOUT} component={About} />
<Route path={routes.CONTACT} component={Contact} />
<Route path={routes.NEWS} component={News} />
<Route component={NotFound} />
</Switch>
</div> :
<p>Loading...</p>
);
}
}
function mapStateToProps(state) {
return state;
}
export default withRouter(connect(
mapStateToProps,
{ ...actions }
)(App));
reducers/index.js
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
export default combineReducers({
pages,
posts,
routing: routerReducer
});
components/Home.js
import React from 'react';
const Home = (props) => {
console.log('home', props);
return (
<div>
This is the home page.
</div>
);
};
export default Home;
You should pass the props to home component like this to make it available there,
<Route path={routes.HOME} exact component={(props)=><Home {...props} newProps={value you want to pass}/> }/>
Since you are using react-router v4 you need to be using react-router-redux v5. See here
This uses a different npm package to react-router-redux installed with:
npm install --save react-router-redux#next
The routing reducer should then have the router key (not routing) in combineReducers.
You will then need to use ConnectedRouter and pass in your history object like so...
render(
<Provider store={store}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</Provider>,
document.getElementById('root')
);
I am using react-router 4 with react-redux. but now I am not able to render any page. I am getting 404 while hitting URL. but console is not showing any error. may be I have colluded something with react-router version 3 but not able to get it what? one more thing here is that my one reducers is being called while store registration though I am not adding reducers in it.and more thing is IndexRoute deprecated in v4?
here is my config.js
import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware,compose } from 'redux'
import { Provider } from 'react-redux'
//import rootReducer from './reducers'
import createLogger from 'redux-logger'
import thunk from 'redux-thunk'
import {BrowserRouter} from 'react-router-dom'
import App from './containers/App'
import promise from "redux-promise-middleware"
import logger from "redux-logger"
import {fetchUsers} from "./action/UserAction"
import {fetchChart} from "./action/ChartAction"
import {fetchNames} from "./action/SearchAction"
import reducer from "./reducers"
import routes from "./routes"
const middleware = applyMiddleware(promise(), thunk, logger())
//const store= createStore(reducer,middleware)
const store= createStore(middleware)
//store.dispatch(fetchUsers());
//store.dispatch(fetchChart());
render(
<Provider store={store}>
<BrowserRouter routes={routes} />
</Provider>,
document.getElementById('root')
)
my routes.js
import App from "./pages/App"
import Users from "./pages/Users"
import Charts from "./pages/Charts"
import React from "react"
import { Route } from "react-router-dom"
export default (
<Route path="/" component={App}>
{/* <IndexRoute component={Users} /> */}
<Route path="/" component={Users}/>
<Route path="charts" name="charts" component={Charts}/>
</Route>
);
my App.js
import {Link} from "react-router"
const App = () =>(
<div>
<h1> this is main page </h1>
<Link to="charts">charts</Link>
</div>
)
export default App
my charts.js
const Chart = () => (
<h1> this is chart </h1>
)
export default Chart
my Users.js
const User = () =>(
<div>
<h1> this is user </h1>
</div>
)
export default User
and reducer is that is being called
import _intialState from "../api/names.js"
const intialValues = {names:['x','y','z','a','b','c','d','e','f'],
searchText:''}
export default function reducer(
state=intialValues,
action){
console.log("search reducer",state)
switch(action.type){
case "SEARCH":{
return Object.assign({},state,{searchText:action.payload})
}
default:
return state;
}
}
As per the react-router documentation, there is no props called routes to BrowserRouter
Instead you can specify the routes to BrowserRouter as children.
children: node
A single child element to render.
Use it like
<BrowserRouter >
{routes}
</BrowserRouter>