What does it meant - Browser history needs a DOM? [duplicate] - javascript

I am trying server side rendering using react-router 4. I am following the example provided here https://reacttraining.com/react-router/web/guides/server-rendering/putting-it-all-together
As per the example on server we should use StaticRouter. When I import as per the example I am seeing StaticRouter as undefined
import {StaticRouter} from 'react-router';
After doing some research online I found I could use react-router-dom. Now my import statement looks like this.
import {StaticRouter} from 'react-router-dom';
However when I run the code I am getting Invariant Violation: Browser history needs a DOM in the browser.
my server.js file code
....
app.get( '*', ( req, res ) => {
const html = fs.readFileSync(path.resolve(__dirname, '../index.html')).toString();
const context = {};
const markup = ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={context} >
<App/>
</StaticRouter>
);
if (context.url) {
res.writeHead(302, {
Location: context.url
})
res.end();
} else {
res.send(html.replace('$react', markup));
}
} );
....
And my client/index.js code
....
ReactDOM.render((
<BrowserRouter>
<App />
</BrowserRouter>
), root);
....
Update v1
Reduced my example to a bear minimum and still getting the same error.
clientIndex.js
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import App from '../App'
ReactDOM.render((
<BrowserRouter>
<App/>
</BrowserRouter>
), document.getElementById('app'))
serverIndex.js
import { createServer } from 'http'
import React from 'react'
import ReactDOMServer from 'react-dom/server'
import { StaticRouter } from 'react-router'
import App from '../App'
createServer((req, res) => {
const context = {}
const html = ReactDOMServer.renderToString(
<StaticRouter
location={req.url}
context={context}
>
<App/>
</StaticRouter>
)
res.write(`
<!doctype html>
<div id="app">${html}</div>
`)
res.end()
}).listen(3000);
App.js
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import routes from "./client/routes";
const App = ( ) => (
<Router>
<Route path="/" exact render={( props ) => ( <div>Helloworld</div> )} />
</Router>
)
export default App;

You need to use different history provider for server side rendering because you don't have a real DOM (and browser's history) on server. So replacing BrowserRouter with Router and an alternate history provider in your app.js can resolve the issue. Also you don't have to use two wrappers. You are using BrowserRouter twice, in app.js as well as clientIndex.js which is unnecessary.
import { Route, Router } from 'react-router-dom';
import { createMemoryHistory } from 'history';
const history = createMemoryHistory();
<Router history={history}>
<Route path="/" exact render={( props ) => ( <div>Helloworld</div> )} />
</Router>
You can now replace StaticRouter with ConnectedRouter which can be used both in client and server. I use the following code to choose between history and export it to be used in ConnectedRouter's history.
export default (url = '/') => {
// Create a history depending on the environment
const history = isServer
? createMemoryHistory({
initialEntries: [url]
})
: createBrowserHistory();
}

In clientIndex.js
Rather than BrowserRouter use StaticRouter.
import { BrowserRouter } from 'react-router-dom';
import { StaticRouter } from 'react-router-dom'

As is essentially noted in the comments, one may hit this error (as I have) by accidentally wrapping your App component in a <BrowserRouter>, when instead it is your client app that should be wrapped.
App.js
import React from 'react'
const App = () => <h1>Hello, World.</h1>
export default App
ClientApp.js
import React from 'react'
import { BrowserRouter } from 'react-router-dom'
import ReactDOM from 'react-dom'
import App from './App'
const render = Component => {
ReactDOM.render(
<BrowserRouter>
<Component />
</BrowserRouter>,
document.getElementById('app')
)
}
render(App)
See also the React Router docs.

Related

Text not displayed in React using Routes

I am fairly new to using react and been following a couple of tutorials on YT, I have ran into a problem with one of them. I copied everything line by line, but my text on 'Home' and 'Login' doesnt display! I get no errors, but the page remains blank.
here is App.js
import React from 'react'
import { Routes, Route, useNavigate } from 'react-router-dom';
import Login from './components/Login';
import Home from './container/Home';
const App = () => {
return (
<Routes>
<Route path="login" element={<Login />} />
<Route path="/*" element={<Home />} />
</Routes>
);
};
export default App;
Also the index.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById('root'),
);
**Then Login.jsx
**
import React from 'react';
const Login = () => {
return (
<div>
Login
</div>
);
};
export default Login;
Finally Home.jsx
import React from 'react';``your text``
const Home = () => {
return (
<div>
Home
</div>
);
};
export default Home;
I know I am missing something, but I cant seem to find it! Any and all help is very much appreciated!
Tried to see if I am using on old version of the BroswerROuter/Routes in React, but I have very little knowledge to see the difference just yet!

React Admin | Uncaught Error: Missing history prop

I am trying to implement react-admin in my project however upon render I get this message
Uncaught Error: Missing history prop. When integrating react-admin inside an existing redux Provider, you must provide the same 'history' prop to the <Admin> as the one used to bootstrap your routerMiddleware. React-admin uses this history for its own ConnectedRouter.
There is very little to be found about this issue and I'm not entirely sure how to go about setting the history. I've tried importing createHistory from 'history/createHashHistory' but then I get this error
Uncaught Could not find router reducer in state tree, it must be mounted under "router"
Is there a way to get this rendering properly? And if so, what would be the proper way to go about configuring the Admin Component's history?
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { createStore, compose, applyMiddleware} from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { BrowserRouter as Router } from 'react-router-dom';
import { reducer } from './redux/reducer';
import * as serviceWorker from './serviceWorker';
const store = createStore(reducer, compose(
applyMiddleware(thunk),
window.navigator.userAgent.includes('Chrome') ?
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() : compose,
),
);
ReactDOM.render(
<React.StrictMode>
<Router>
<Provider store={store}>
<App />
</Provider>
</Router>
</React.StrictMode>,
document.getElementById('root')
);
AdminPage.js
import { Admin, Resource } from 'react-admin';
import jsonServerProvider from 'ra-data-json-server';
const dataProvider = jsonServerProvider('http://localhost:3000');
const AdminPage = () => {
return (
<Admin dataProvider={dataProvider}>
<Resource name="services" />
</Admin>
)
}
export default AdminPage;
App.js
import React from 'react';
import './App.css';
import AdminPage from './components/AdminPage';
import { Switch, Route } from 'react-router-dom';
const App = () => {
return (
<div className="app">
<Switch>
<Route exact path='/manage' component={ AdminPage } />
</Switch>
</div>
);
}
export default App;
The proper way to write a reducer in this case is documented at https://marmelab.com/react-admin/CustomApp.html#using-an-existing-redux-provider.
But from what I see, you don't need one. You just added the thunk middleware, which is useless in react-admin as it already handles sagas.

My react route is redirecting to localhost:3000 and not the page it should redirect to

I have 2 components both are exactly the same. one is redirected to when I click on a Navlink inside of my navbar that I created using react-bootstrap. The other component that is exactly the same just redirects to localhost:3000 and not "./member" when I click on the html button that should redirect to that component. Please help me.
the html button and the function to redirect look like
import {Link, Route, withRouter, useHistory} from 'react-router-dom'
const Posts = (props) => {
const dispatch = useDispatch();
const history = useHistory();
const getProfile = async (member) => {
// const addr = dispatch({ type: 'ADD_MEMBER', response: member })
console.log(member)
history.push('/member')
}
return (
<div>
<button onClick={() => getProfile(p.publisher)}>Profile</button>
</div>
)
}
export default withRouter(Posts);
The routes.js looks like
const Routes = (props) => {
return (
<Switch>
<Route path="/member" exact component={Member} />
</Switch>
)
}
export default Routes
The component that I am trying to redirect to is exactly the same as one that is redirected to and working when I click on it from the navlink. I have downgraded to history 4.10.1
My index.js is
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Router, Route } from 'react-router-dom';
import * as history from 'history';
import * as serviceWorker from './serviceWorker';
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import rootReducer from './reducers'
const store = createStore(rootReducer)
const userHistory = history.createBrowserHistory();
ReactDOM.render(
<Provider store = {store}>
<Router history={userHistory}>
<BrowserRouter>
<Route component={App} />
</BrowserRouter>
</Router>
</Provider>,
document.getElementById('root'));
serviceWorker.unregister();
When I wrap the app route in the url goes to ./member but it does not load.
<Switch>
<Route path="/" exact component={app} />
<Route path="/member" component={Member} />
</Switch>
<button onClick={() => history.push(`/${p.publisher}`)}>Profile</button>

Warning: Failed context type: The context `store.isRequired` is marked as required in `Routing`, but its value is `undefined`

I'm having an issue with react-redux Provider:
I moved our router out of our index.js to a routing.js file. I used a Provider to give my Routing component knowledge of the store but I'm getting a strange warning before the execution reaches the render method :
Warning: Failed context type: The context `store.isRequired` is marked as required in `Routing`, but its value is `undefined`.
This happens even if I get rid of the .isRequired in Routing.contextTypes. Moreover if I put a debugger statement at the beginning of the render function, it appears that this.contextisn't undefined and my app is working like a charm. I'm wondering if I did something wrong or if it could possibly be a bug of react-redux Provider or something.
Here is my code:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { setLanguage } from 'redux-i18n';
import I18n from 'redux-i18n/immutable';
import configureStore from './store/configure_store';
import { Routing } from './routing';
import translations from './translations';
import '../scss/index.scss';
const store = configureStore();
store.dispatch(setLanguage(navigator.language));
ReactDOM.render(
<Provider store={ store }>
<I18n translations={ translations }>
<Routing />
</I18n>
</Provider>,
document.getElementById("root")
);
routing.js (simplified for reading purpose)
import React from 'react';
import { Route, IndexRedirect, IndexRoute, Router, browserHistory } from 'react-router';
import AppContainer from './components/App/App';
import Base from './components/Root/Base';
import BaseInProject from './components/App/BaseInProject';
import { ProjectListContainer } from './components/App/Projects/ProjectsList';
export class Routing extends React.Component {
render() {
const { store } = this.context;
const beforeAppRouteEnter = (nextState, replace, callback) => {
// This function needs to store.dispatch some stuff
};
// Some other router functions
const routes = (
<Route path='/' component={ Base }>
<Route component={ AppContainer } onEnter={ beforeAppRouteEnter }>
<IndexRoute component={ ProjectListContainer } />
// Some other routes
<IndexRedirect to='media' />
</Route>
</Route>
</Route>
);
return (
<Router history={ browserHistory }>{ routes }</Router>
);
}
}
Routing.contextTypes = {
store: React.PropTypes.shape(React.PropTypes.any)
};
Thanks!

export default not working webpack, reactjs

I'm new to webpack, I'm starting to build an app using webpack and react 15, however it's like the export default is not working properly because I got an error as the App component is not found:
5:9 App not found in './components/App' import/named
Below the code of my index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import {Router,Route,IndexRoute,browserHistory} from 'react-router';
import { Provider } from 'react-redux';
import {App} from './components/App';
import {HomePage} from './components/HomePage';
import configureStore from './store/configureStore.js';
import { syncHistoryWithStore } from 'react-router-redux';
const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store);
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={HomePage}/>
</Route>
</Router>
</Provider>,
document.getElementById('app')
);
and the code of my App.js placed under components folder:
import React, { PropTypes } from 'react';
const App = (props) => {
return (
<div>
{props.children}
</div>
);
};
App.propTypes = {
children: PropTypes.element
};
export default App;
Can anyone see the problem? Looks like this type of export is not supported and I have to enable something?
Any help is appreciatted!!
Omit the curly braces:
import App from './components/App';
That's the trick with default, see.

Categories

Resources