How to render a react component on landing? - javascript

I am new to react app trying to add a component and loading when app opens but it is showing in console Matched leaf route at location "/" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page what is implemented wrong please help
App.js
import React from 'react';
import './app.css';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import JOB_DESC from './job_desc';
function App() {
return (
<Router>
<Routes>
<Route exact path='/' component={JOB_DESC} />
</Routes>
</Router>
)
}
export default App;
job_desc.js
import React, { Component } from 'react';
import './app.css';
import ReactImage from './react.png';
export default class JOB_DESC extends Component {
state = { data: null };
componentDidMount() {
fetch('/api/getUsername')
.then(res => res.json())
.then(res => this.setState({ data : res.data}));
}
render() {
const { data } = this.state;
console.log("DATA", data);
return (
<div>
<h1>Test</h1>
{username ? <h1>{`Hello ${username}`}</h1> : <h1>Loading.. please wait!</h1>}
<img src={ReactImage} alt="react" />
</div>
);
}
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));

Try adding <JOB_DESC /> as component in the Route

Related

How to render react class component with React HashRouter and Apollo client?

I am working at a project in which I must use only React class components and I am fetching data from an Apollo server.
The problem is that in Chrome is rendering only the Navbar.jsx. When I am navigating on one of the links nothing is on the screen. Also there is not any error in the console.
Could somebody help me?
Thanks!
This is Index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
} from "#apollo/client";
import { HashRouter } from 'react-router-dom';
export const client = new ApolloClient({
uri: ' http://localhost:4000/',
cache: new InMemoryCache()
});
ReactDOM.render(
<React.StrictMode>
<HashRouter >
<ApolloProvider client={client}>
<App />
</ApolloProvider>
</HashRouter>
</React.StrictMode>,
document.getElementById('root')
);
reportWebVitals();
Here is App.js :
import React, { Component } from 'react'
import './App.css';
import { Switch, Route} from 'react-router-dom'
import Navbar from './Components/Navbar';
import Bikes from './Pages/Bikes';
import Books from './Pages/Books';
import { client } from './index';
import {GET_QUERY} from './GraphQl/Queries'
class App extends Component {
state={
currencies: [],
}
componentDidMount = async ()=>{
const response = await client.query({
query:GET_QUERY
})
this.setState({
currencies:response.data.currencies
})
}
render() {
return (
<div className="App">
<Navbar currencies={this.state.currencies}/>
<Switch>
<Route exact path="/bikes" component={Bikes} />
<Route exact path="/books" component={Books} />;
</Switch>
</div>
);
}
}
export default App;
Here is Navbar.jsx :
import React, { Component } from 'react'
import {Link} from 'react-router-dom'
import styled from 'styled-components'
import { withRouter } from 'react-router';
const StyledLink = styled(Link)`
`;
class Navbar extends Component {
render() {
return (
<nav>
<div>
<ul>
<li>
<StyledLink to="/bikes" replace>Bikes</StyledLink>
</li>
<li>
<StyledLink to="/books" replace>Books</StyledLink>
</li>
</ul>
</div>
</nav>
)
}
}
export default withRouter(Navbar)
and one of the pages, Bikes.jsx:
import React, { Component } from 'react'
import { client } from '../index'
import { GET_QUERY } from '../GraphQl/Queries'
import { CATEGORY_VAR } from '../GraphQl/Variables'
class Bikes extends Component {
state={
bikesArt: []
}
componentDidMount = async ()=>{
const response = await client.query({
query: GET_QUERY,
variables: CATEGORY_VAR
})
this.setState({
bikesArt:response.data.category.products
})
}
render() {
return (
<div>
<h1>Bikes</h1>
</div>
)
}
}
export default Bikes
Solved it. It was the CSS. The navbar was covering the only <h2> tag from the page

when use route in React and route a stateless function nothing rendered

here is the code
when i try to route at localhost:3000/a nothing appears
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router } from "react-router-dom";
import Route from "react-router/Route";
//import Home from "./components/Home";
const Home = () => {
return (
<div>
<h6>East or West home is The best </h6>
</div>
);
};
class App extends Component {
state = {};
render() {
return (
<Router>
<div className="app">
<Route path="/a" Component={Home} />
</div>
</Router>
);
}
}
export default App;
ReactDOM.render(<App />, document.getElementById("root"));
use Route instead of Router and wrap your App under Router like below
import React, { Component } from "react";
import ReactDOM from "react-dom";
import { Route, Switch } from "react-router-dom";
import { BrowserRouter as Router } from 'react-router-dom';
const Home = () => {
return (
<div>
<h6>East or West home is The best </h6>
</div>
);
};
class App extends Component {
state = {};
render() {
return (
<div className="app">
<Route>
<Route path="/a" Component={Home}
/>
</div>
);
}
}
export default App;
ReactDOM.render(<Router><App /></Router>, document.getElementById("root"));

Why I can not see the result of router while component is present React

I use react router and I can see Signup link on the screen
But when I press this link nothing heppends , Tell me why please.
Main.js
import ReactDOM from 'react-dom';
import React from 'react';
//import { Router, Route, hashHistory } from 'react-router';
import { BrowserRouter, Route } from 'react-router-dom'
import App from './components/App.jsx';
import WizardIndex from './components/WizardIndex.js';
ReactDOM.render(
<BrowserRouter>
<App path="/" component={App}>
<Route path="/signup" component={ WizardIndex }/>
</App>
</BrowserRouter>,
document.getElementById('mount-point')
);
App.jsx
import React from 'react';
import { Link } from 'react-router-dom';
const App = React.createClass({
render: function(){
return (
<div className='App'>
<div className='menu-bar'>
<div className='menu-item'>
<h3>App</h3>
<Link to='/signup'>Signup</Link>
</div>
<div className='content'>
{ this.props.children }
</div>
</div>
</div>
);
}
});
export default App;
WisardIndex.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { Values } from "redux-form-website-template";
import store from "./store";
import showResults from "./showResults";
import WizardForm from "./WizardForm";
const Index = React.createClass({
render(){
return (
<h3>123</h3>
);
}
});
export default Index;
I can not understand I setting up this.props.children in App.jsx. I include Route And Think everything doing by the rules, but nothing in the result
First of all first, if you can compile and run given source code then that means you are working with React's very old version that's because of there is no such thing as React.createClass anymore. Update it.
Second I think you misunderstood the concept of react-router-dom. That line contains <App path="/" ... effects nothing because of you cannot assign path nor component props to App. If you are rendering App component as a child of BrowserRouter that means "Im surrounding every route with one component and it's the App Component. App component should render every route as a child."
I'm assuming that you will create your components as Class Components then the right code would be like this :
Main.js :
import ReactDOM from 'react-dom';
import React from 'react';
//import { Router, Route, hashHistory } from 'react-router';
import { BrowserRouter, Route } from 'react-router-dom'
import App from './components/App.jsx';
import WizardIndex from './components/WizardIndex.jsx';
ReactDOM.render(
<BrowserRouter>
<App>
<Route path="/signup" component={ WizardIndex }/>
</App>
</BrowserRouter>,
document.getElementById('mount-point')
);
App.jsx :
import React from "react";
import { Link } from "react-router-dom";
class App extends React.Component {
render() {
const { children } = this.props;
return (
<div className="App">
<div className="menu-bar">
<div className="menu-item">
<h3>App</h3>
<Link to="/signup">Signup</Link>
</div>
<div className="content">{children}</div>
</div>
</div>
);
}
}
export default App;
WizardIndex.jsx :
import React from "react";
import ReactDOM from "react-dom";
class WizardIndex extends React.Component {
render() {
return <h3>123</h3>;
}
}
export default WizardIndex;
Actually i have written it for you in codesandbox, you can check the working code for your situation here:
https://codesandbox.io/s/rr1nv610wp

React setting up a one-off route

I have an application that uses the same layout for all routes... except one.
One route will be completely different than all others.
So the entire application will have a menu, body, footer, etc.
The one-off route will not have any of that and be a completely separate thing.
How should I set this kinda thing up in a react app? Everything I've ever seen/done always has one main wrapping element that has the routes rendered as children.
index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import configureStore from './store'
import App from './components/App'
// import registerServiceWorker from './registerServiceWorker'
import { unregister } from './registerServiceWorker'
const preloadedState = window.__PRELOADED_STATE__ ? window.__PRELOADED_STATE__ : {}
// console.log('window.__PRELOADED_STATE__', window.__PRELOADED_STATE__)
delete window.__PRELOADED_STATE__
const Store = configureStore(preloadedState)
const rootEl = document.getElementById('root')
ReactDOM.hydrate(
<Provider store={Store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
rootEl
)
if(module.hot){
module.hot.accept('./components/App', () => {
ReactDOM.hydrate(
<Provider store={Store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>,
rootEl
)
})
}
// registerServiceWorker()
unregister()
App.js
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
// Components
import AppHelmet from './AppHelmet'
import Notices from './Notices'
import Header from './Header'
import Body from './Body'
import Footer from './Footer'
// Site state
import { getSiteInfo } from '../store/actions/siteInfo'
import { REACT_APP_SITE_KEY } from '../shared/vars'
// CSS
import '../css/general.css'
class App extends Component {
initialAction() {
this.props.getSiteInfo(REACT_APP_SITE_KEY)
}
componentWillMount() {
// On client and site info has not been fetched yet
if(this.props.siteInfo.site === undefined){
this.initialAction()
}
}
render() {
return (
<div>
<AppHelmet {...this.props} />
<Notices />
<div className="body">
<Header />
<Body />
</div>
<Footer />
</div>
)
}
}
const mapStateToProps = (state) => {
return {
siteInfo: state.siteInfo,
user: state.user
}
}
const mapDispatchToProps = (dispatch) => {
return {
getSiteInfo: (siteKey) => dispatch(getSiteInfo(siteKey))
}
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App))
Body.js
import React, { Component } from 'react'
import { Switch, Route } from 'react-router-dom'
import routes from '../shared/routes'
class Body extends Component {
render() {
return (
<Switch>
{routes.map((route, i) => <Route key={i} {...route} />)}
</Switch>
)
}
}
export default Body
So, as you can see the index.js entry point will render <App />. <App /> will render the main layout, including <Body />, which renders all routes and content.
Cool.
But seeing as I don't want this one-off to render the <App /> layout, I'm not sure how to set this up from index.js. I'm sure it's simple and I'm just not seeing the answer.
One way to achieve what you want is to listen to the router.
You can add the listener into the components you want to hide.
When the listener detects you're on a view where you do not want the components to show, simply don't render them for that view.

Meteor - Simple react router throwing errors

I have basically copied code straight from the documentation, and it is throwing a peculiar error.
Warning: Failed prop type: The prop `history` is marked as required in
`Router`, but its value is `undefined`.
in Router
Here is my code:
client/main.jsx
import React from "react"
import { render } from "react-dom"
import { Meteor } from "meteor/meteor"
import { renderRoutes } from "../imports/ui/Routes.jsx"
Meteor.startup(() => {
render(renderRoutes(), document.getElementById('react-root'))
})
imports/ui/Routes.jsx
import React from 'react'
import { render } from "react-dom"
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
// route components
import App from "./App.jsx"
export const renderRoutes = () => (
<Router history={browserHistory}>
<Route path="/" component={App} />
</Router>
)
imports/ui/App.jsx
import React, { Component } from 'react'
import TopBar from "./components/TopBar.jsx"
import LeftMenuContainer from "./components/LeftMenuContainer.jsx"
import LivePurchases from "./components/LivePurchases.jsx"
// App component - represents the whole app
export default class App extends Component {
render() {
return (
<div className="App">
<div className="flexWrapperGlobal">
<TopBar/>
<div className="contentContainer">
<LeftMenuContainer/>
<div className="bodyContainer">
<LivePurchases/>
<div className="siteContentContainer">
{this.props.children || "test"}
</div>
</div>
</div>
</div>
</div>
)
}
}
It appears that it should not be giving this error, as I am setting the prop at history={browserHistory}
Switch over to the example from the React Docs,
imports/ui/Routes.jsx
import React from 'react'
import { render } from "react-dom"
import { Router, Route, IndexRoute } from 'react-router'
import createBrowserHistory from 'history/createBrowserHistory'
// route components
import App from "./App.jsx"
const history = createBrowserHistory()
export const renderRoutes = () => (
<Router history={history}>
<Route path="/" component={App} />
</Router>
)

Categories