I have an app which just loads a blank page on start up, yet refreshing the page causes it to load correctly.
This is what I'm trying:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './Assets/css/app.css';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
window.processIntent = intent => {
...cordova stuff
};
window.setupAltIntent = () => {
...cordova stuff
};
function startApp() {
window.intentUrlToPrint = '';
window.setupAltIntent();
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
}
if (!window.cordova) {
startApp();
} else {
document.addEventListener('deviceready', startApp, false);
}
App.js
import React, { Component } from 'react';
import AppActivity from './Views/activity/AppActivity';
import Header from './Components/header';
import AppRouter from './AppRouter';
class App extends Component {
componentDidMount() {
if (navigator.splashscreen) {
navigator.splashscreen.hide();
}
}
render() {
return (
<div>
<div>
<Header />
<AppRouter />
</div>
<AppActivity />
</div>
);
}
}
export default App;
AppRouter.js
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Home from './Pages/Home';
import Contact from './Pages/Contact';
import LogInForm from './Pages/RegisterAndLogin/LogIn';
const AppRouter = () => (
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/contact" component={Contact} />
<Route path="/login" component={LogInForm} />
</Switch>
</div>
);
export default AppRouter;
Header.js
import React, { Component } from 'react';
import HeaderNotLoggedIn from './Headers/HeaderNotLoggedIn';
import HeaderLoggedIn from './Headers/HeaderLoggedIn';
class Header extends Component {
constructor(props) {
super(props);
this.isLoggedOn = this.isLoggedOn.bind(this);
}
isLoggedOn() {
return localStorage.getItem('user');
}
render() {
const header = this.isLoggedOn() ? <HeaderLoggedIn /> : <HeaderNotLoggedIn />;
return <div>{header}</div>;
}
}
export default Header;
Quite new to react, is there anything I'm missing here?
Why does the app only load correctly on page refresh?
I don't have a way to to solve your exact problem, because there are a lot of components, logic, and connections I don't have access to, and so I have to make guesses about. I assume that setupAltIntent returns a promise (though it doesn't totally matter if it does something else). In App I set it up to conditionally render Header once the data has been loaded into the state, which happens when setState is called after the promise is resolved.
Hopefully this gets you far enough to figure out what exactly you need for your own solution.
Link to my solution:
Related
I have to combine use of Redux and React Router.
I tried react Router alone first and when I was clicking my images I was correctly redirected.
I followed redux tutorial and now when I click my images, I change the address (ex: http://localhost:3000/contact) but nothing displays as if the component was empty.
Root.js
import React from 'react';
import './index.css';
import PropTypes from 'prop-types'
import ReactDOM, { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom'
import App from './App'
import Users from './users'
import Book from './Book'
import Notfound from './notfound'
import { Provider } from 'react-redux';
import Store from './redux/Store/store'
import * as serviceWorker from './serviceWorker';
const Root = ({ store }) => (
<Provider store = { Store }>
<Router>
<div>
<Switch>
<Route exact path="/:filter?" component={App} />
<Route path="/users" component={Users} />
<Route path="/book" component={Book} />
<Route path='/manual' component={() => { window.location = 'https://------'; return null;} }/>
<Route path='/contact' component={() => { window.location = 'https://-------'; return null;} }/>
<Route component={Notfound} />
</Switch>
</div>
</Router>
</Provider>
)
Root.propTypes = {
store: PropTypes.object.isRequired
}
serviceWorker.unregister();
export default Root
index.js:
import React from 'react'
import { render } from 'react-dom'
import { createStore } from 'redux'
import myReducer from './redux/Reducers/myReducer'
import Root from './Root'
const store = createStore(myReducer)
render(<Root store={store} />, document.getElementById('root'))
App.js:
import React from 'react'
import { Route, Link, Redirect, withRouter, BrowserRouter as Router } from 'react-router-dom'
import logo from './images/logo.png';
import book from './images/book.png';
class App extends React.Component {
constructor() {
super();
this.state = {
date: new Date()
};
}
render() {
const { date } = this.state;
return (
<div>
<img src={logo} />
<img src={book} onClick={() => this.props.history.push('/book')}/>
<img src={call} onClick={() => this.props.history.push('/contact')}/>
</div>
)
}
}
export default App
Do you know what is wrong ?
A few things I noticed:
When using react router you shouldn't use window.location to redirect since this reloads the whole page. The <Redirect> component from react-router is a better choice here.
Also you shouldn't use the component prop on the <Route>-component for things that aren't actually components, as there's the render prop for that (more on that here).
Furthermore: <Route exact path="/:filter?" component={App} /> is not going to work since :filter? is looking for a variable and exact is looking for an exact match. Moreover you probably shouldn't put the flexible one first since it's going to match every route that you throw at it. So all the following routes are practically unreachable.
Hi I am new in react and I want to implement routing with Loadable, But Its not working Its showing blank page when either http://localhost:3000/user or http://localhost:3000/
Could you please correct me where I am doing wrong.
I am also getting-
Warning: Failed prop type: Invalid prop component of type string supplied to Route, expected function.
My codes are:
home.js
import React, { Component } from 'react';
import { Link} from 'react-router-dom';
class Home extends Component {
render() {
return (
<div>
<h1>Welcome to the Tornadoes Website!</h1>
<h5><Link to="/user">User</Link></h5>
</div>
);
}
}
export default Home;
user.js:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class User extends Component {
render() {
return (
<div>
<ul>
<li>6/5 # Evergreens</li>
<li>6/8 vs Kickers</li>
<li>6/14 # United</li>
<li><Link to="/">Home</Link></li>
</ul>
</div>
)
}
}
export default User;
App.js:
import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { history } from './helpers/history';
import Loadable from 'react-loadable';
import './App.css';
const Loading = () => <div> Loading... </div>;
const Home = Loadable({
loader: () => import('./components/home-component/home'),
loading: Loading
});
const User = Loadable({
loader: () => import('./components/user-component/user'),
loading: Loading
});
class App extends React.Component {
render() {
return (
<Router history={history}>
<Switch>
<Route exact path="/" component="Home" />
<Route path="/user" component="User" />
</Switch>
</Router>
);
}
}
export default App;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { BrowserRouter } from 'react-router-dom'
ReactDOM.render((
<BrowserRouter>
<App />
</BrowserRouter>
), document.getElementById('root'))
registerServiceWorker();
I see you are doing this: <Route exact path="/" component="Home" /> which should be <Route exact path="/" component={Home} /> since you want to use that variable, it's impossible to reference by String when he can't know which Component you want. I hope this helps
This looks to me like there is a isRequired propType that you have missed when calling your component. Can you post your components here as well?
Unfortunately, I can't get React Router to work in my custom meteor boilerplate and I really can't figure out why. Here's all the files that could potentially be relevant to the problem:
\client\main.js:
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';
import { renderRoutes } from '../imports/startup/client/routes.jsx';
Meteor.startup(() => {
render(renderRoutes(), document.getElementById('app'));
});
\imports\startup\client\routes.jsx:
import React from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
// route components
import App from '../../ui/App.jsx';
export const renderRoutes = () => (
<Router>
<div>
<Route path="/" component={App} />
</div>
</Router>
);
\imports\ui\App.jsx
import React from 'react';
import { withTracker } from 'meteor/react-meteor-data';
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<h1>Hey!</h1>
);
}
}
export default withTracker(() => {
return {
};
})(App);
Any idea why the error message might occur? Thanks!
Not sure what version of meteor and react you are using but tha's how i did it on the last project i had.
Try this changes:
import {Router, Route, browserHistory} from 'react-router';
export const renderRoutes = () => (
<Router history={browserHistory}>
<div>
<Route path="/" component={App} />
</div>
</Router>
);
I am trying to render a specific component inside of another component based on React, React-Router v4, and Redux in my main 'panel' wrapped in a fixed header and sidebar component.
For example when I select an item from the sidebar, I to render the Detail panel and and load the details based on the id, like: <Route path='/item/:id' component={ItemDetail} />
routes.js
import React, { Component } from 'react';
import { RouteHandler, Switch, Route, DefaultRoute } from 'react-router';
import App from './containers/App';
import Login from './containers/Login';
import LobbyDetail from './components/LobbyDetail';
export default (
<Switch>
<Route exact path="/" component={App} />
<Route exact path="/login" component={Login} />
</Switch>
);
app.js:
import React, { Component } from 'react'
import { Router, Route, Link } from 'react-router'
import { connect } from 'react-redux'
import PropTypes from 'prop-types';
import auth from '../actions/auth';
import Sidebar from '../Components/Sidebar'
class App extends Component {
static propTypes = {
};
/**
*
*/
render() {
const { ... } = this.props
return (
<div className="container-fluid">
<div className="row">
{* I WANT TO RENDER DYNAMIC COMPONENT HERE *}
</div>
<Sidebar currentUser={currentUser}
logout={logout}
/>
</div>
);
}
}
// ...
export default connect(mapStateToProps, mapDispatchToProps)(App)
index.js (basically main app):
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { createMemoryHistory } from 'history';
import routes from './routes';
import configureStore from './store/store.js';
import { AppContainer } from 'react-hot-loader';
const syncHistoryWithStore = (store, history) => {
const { routing } = store.getState();
if (routing && routing.location) {
history.replace(routing.location);
}
};
const initialState = {};
const routerHistory = createMemoryHistory();
const store = configureStore(initialState, routerHistory);
syncHistoryWithStore(store, routerHistory);
const rootElement = document.querySelector(document.currentScript.getAttribute('data-container'));
const render = () => {
ReactDOM.render(
<AppContainer>
<Provider store={store}>
<ConnectedRouter history={routerHistory}>
{routes}
</ConnectedRouter>
</Provider>
</AppContainer>,
rootElement
);
}
render();
if (module.hot) { module.hot.accept(render); }
What you're looking for is parameterized routing. Make a <Route/> like the following: <Route path='/item/:id' component={ MyComponent } />.
Now in MyComponent you can use the value of props.match.params.id to conditionally render, or if you're trying to load async data based on the value of :id; You can use the componentWillReceiveProps life cycle method and dispatch an action based on the value of this.props.match.params.id.
Note: <Link to='/item/some-item'/> will set the value of match.params.id to 'some-item'.
I'm using react-router to direct a set of cards on the main page, to other individual pages. However, when I click on a card, the new page renders underneath the set of cards, when what I want is to render ONLY the new page. I think the problem may have to do with that my App.js holds the main page inside it, but I don't know where I should put it, if there should be a separate link to it, etc? I would appreciate any help! Thank you
here is the code for the App.js
import React from 'react';
import Routes from '../containers/routes.js';
import ProjectCards from '../containers/project_cards.js';
export default class App extends React.Component {
render() {
return(
<div>
<ProjectCards />
<Routes />
</div>
);
}
}
here is the main container:
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 routes container:
import React from 'react';
import Project1 from '../components/project1.js';
import { connect } from 'react-redux';
import { Route, Switch } from 'react-router-dom';
import { withRouter } from 'react-router';
class Routes extends React.Component{
render() {
var createRoutes = this.props.projects.map((project, i) => {
return <Route key={i} exact path={`/${project.title}`} exact component={Project1}/>
});
return (
<Switch>
{createRoutes}
</Switch>
);
}
}
function mapStateToProps(state) {
return {
projects: state.projects
};
}
export default withRouter(connect(mapStateToProps)(Routes));
Set you App file as entry for all components e.g
import React, { Component } from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import Home from '../../ui/components/user/home/Home.jsx';
import Header from './header/Header.jsx';
import Fakebook from '../../ui/components/user/fakebook/Fakebook.jsx';
import Dashboard from '../../ui/components/user/dashboard/Dashboard.jsx';
import NotFound from '../../ui/pages/NotFound.jsx';
export default class App extends Component{
render(){
return (
<BrowserRouter>
<div>
<Header />
<Switch>
<Route exact path="/" component={Fakebook}/>
<Route exact path="/Home" component={Home}/>
<Route exact path="/Dashboard" component={Dashboard} />
<Route exact path="/Dashboard/:userId" component={Dashboard}/>
<Route component={NotFound}/>
</Switch>
</div>
</BrowserRouter>
)
}
}
Now if you studied it you will notice a <Header /> component which is not in a route. I did it that way because my header is constant across my whole app.
This is how I setup my route I make my Route the second file after the index.js file so all my route can be visible.