Cannot route to required React Component using React-Router-DOM - javascript

I am trying to route to the component "Products" from my Homepage as per the product id from the item list from the Home Component. My page is getting routed to 'localhost:3000/id' but it is not getting the Products component. There are no errors that I faced. I fetched the data from the fake API and displayed the products on the home page. After clicking the product I want the page to route to "Product" component. The address is routing as expected but the component is not loading.
import React, { Component } from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import Products from "./Products";
interface Props {}
interface ResponseData {
id: number;
price: number;
description: string;
image: string;
}
interface State {
response: ResponseData[];
}
export default class Home extends React.PureComponent<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
response: [],
};
}
getProductsData = async () => {
const apiResponse = await fetch("https://fakestoreapi.com/products");
console.log(apiResponse);
const responseData = await apiResponse.json();
this.setState({
response: responseData,
});
};
componentDidMount() {
this.getProductsData();
}
render() {
const { response } = this.state;
if (response.length === 0) {
return <div className="loader">Loading the items....... </div>;
}
return (
<div >
<div className="product-list">
{response.map((resp) => (
<Switch>
<Link className = "product-cards"
to={`${resp.id}`} >
<Route path={`${resp.id}`} component={Products}/>
<div className="product-cards">
<img src={resp.image} />
<div className="product-description">{resp.description}</div>
<div className="product-price">{resp.price}</div>
</div>
</Link>
</Switch>
))}
</div>
</div>
);
}
}

You probably need to replace your switch routes to App component and in this Home component just use a Link to redirect to the path you want.
function App() {
return (
<Switch>
<Route exact path="/" component={ Home } />
<Route path="/:id" component={ Products } />
</Switch>
);
}
Home component return should be something like this:
return (
<div className="product-list">
{response.map((resp) => (
<Link
className = "product-cards"
to={`/${resp.id}`}
>
<div className="product-cards">
<img src={resp.image} />
<div className="product-description">{resp.description}</div>
<div className="product-price">{resp.price}</div>
</div>
</Link>
))}
</div>
);

Related

Why the Link tag in react routers is not showing me the desired page?

I was trying to fetch data through a news API and there were different categories of news with the help of react-router I want to show news of different categories, the link tag is working as it is changing the local host URL but the page is not showing the particular news category. Can anyone help me out?
This is the App.js,
import './App.css';
import React, { Component } from 'react'
import Navbar from './COMPONENTS/Navbar';
import News from './COMPONENTS/News';
import {
BrowserRouter,
Routes,
Route,
} from "react-router-dom";
export default class App extends Component {
render() {
return (
<>
<BrowserRouter>
<Navbar/>
<News category="general"/>
<Routes>
<Route path="/business" element={<News key="business" category="business"/>}></Route>
<Route path="/sports" element={<News key="sports" category="sports"/>}></Route>
<Route path="/health" element={<News key="health" category="health"/>}></Route>
<Route path="/politics" element={<News key="politics" category="politics"/>}></Route>
</Routes>
</BrowserRouter>
</>
)
}
}
This is the VerticalNav.jsx file, here are all the links,
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
export default class VerticalNav extends Component {
render() {
return (
<>
<nav className="navbar2">
<ul className="ul_list">
<li className="vertical_comp">
<Link className="avertical_comp" to="/business">Business</Link>
</li>
<li className="vertical_comp">
<Link className="avertical_comp" to="/sports">Sports</Link>
</li>
<li className="vertical_comp">
<Link className="avertical_comp" to="/health">Health</Link>
</li>
</ul>
</nav>
</>
)
}
}
And this is the file where I am using props,
import React, { Component } from 'react'
import NewsItem from './NewsItem'
import Spinner from './Spinner';
import VerticalNav from './Verticalnav';
import PropTypes from 'prop-types';
export default class News extends Component {
static defaultProps = {
category : 'general',
}
static propTypes = {
category : PropTypes.string,
}
constructor() {
super();
this.state = {
article: [],
page: 1,
loading: false,
}
}
async componentDidMount() {
this.setState({
loading: true
})
let url = `https://newsapi.org/v2/top-headlines? country=in&category=${this.props.category}&
apiKey=6aeca0faebbd45c1a1ec3c463f703ebb`;
let data = await fetch(url);
let parseData = await data.json();
this.setState({
article: parseData.articles,
loading: false
});
}
handleNext = async () => {
let url = `https://newsapi.org/v2/top-headlines?
country=in&category=${this.props.category}&apiKey=6aeca0faebb
d45c1a1ec3c463f703ebb&page=${this.sta
te.page + 1}`;
this.setState({ loading: true });
let data = await fetch(url);
let parseData = await data.json();
this.setState({
page: this.state.page + 1,
article: parseData.articles,
loading: false
})
console.log(this.state.page);
}
handlePrevious = async () => {
let url = `https://newsapi.org/v2/top-headlines?
country=in&category=${this.props.category}&apiKey=6aeca0faebbd45c1
a1ec3c463f703ebb&page=${this.sta
te.page - 1}`;
let data = await fetch(url);
let parseData = await data.json();
this.setState({
page: this.state.page - 1,
article: parseData.articles,
loading: false
})
}
render() {
return (
<>
<div className="vertical">
<VerticalNav/>
<div class="card1">
<h1 className='mainheading' >THE PAHADI PRESS HEADLINES OF THE DAY</h1>
<div class="row row1">
{this.state.loading && <Spinner />}
{this.state.article.map((e) => {
return <div class="col-md-4 colu" key={e.url} >
<NewsItem title={e.title} decription={e.description} imageUrl={e.urlToImage}
newsUrl={e.url}
newsauthor={e.author} source={e.source.name} />
</div>
})
}
</div>
</div>
</div>
</>
)
}
}
Try to move the general News component inside the Routes:
return (
<>
<BrowserRouter>
<Navbar />
<Routes>
<Route
path='/'
element={<News key='general' category='general' />}
></Route>
<Route
path='/business'
element={<News key='business' category='business' />}
></Route>
<Route
path='/sports'
element={<News key='sports' category='sports' />}
></Route>
<Route
path='/health'
element={<News key='health' category='health' />}
></Route>
<Route
path='/politics'
element={<News key='politics' category='politics' />}
></Route>
</Routes>
</BrowserRouter>
</>
);

ReactJS - Issues about Dynamic Routes

I have these components. I want to turn every into a dynamic url. For example, when accessing in the browser, http://localhost:3000/houses/1 I want to appear the House 1.
The other things in the application are working fine. I just want to solve this problem of implementing dynamic routes.
The data is fetched from a json file
db.json file
[
{
"houseId": 1,
"name": "House 1",
"photos": [
"house1_001.jpg",
"house1_002.jpg",
"house1_003.jpg",
"house1_004.jpg"
]
},
{
"houseId": 2,
"name": "House 2",
"photos": [
"house2_001.jpg",
"house2_002.jpg",
"house2_003.jpg",
"house2_004.jpg"
]
},
{
"houseId": 3,
"name": "House 3",
"photos": [
"house3_001.jpg",
"house3_002.jpg",
"house3_003.jpg",
"house3_004.jpg"
]
}
]
Router Component
import React from 'react';
import { BrowserRouter as Router, Route, NavLink } from 'react-router-dom'
import App from './App'
import Intro from './Intro'
import Houses from './Houses'
import House from './House'
export default props => (
<Router>
<Route exact path='/' render={() => <App />} >
<Route exact path='/intro' render={() => <Intro />} />
<Route exact path='/houses' render={() => <Houses />} />
<Route exact path='/houses/:houseId' render={(props) => <House {...props} />} />
</Route>
</Router>
)
Houses Component
import React, { Component } from 'react'
import House from './House'
var data = require('./db.json');
class Houses extends Component {
constructor(props) {
super(props);
this.state = {
houses: []
};
}
componentDidMount() {
this.setState({
houses: data
})
}
render() {
const { houses } = this.state;
return (
<div className="content house">
{
houses.map((house, index) => {
return (
<div>
<House house={house} />
</div>
)
})
}
</div>
)
}
}
export default Houses
**House Component**
import React, { Component } from 'react';
class House extends Component {
constructor(props) {
super(props)
this.state = {
houseId: ""
}
}
componentDidMount() {
this.setState({
houseId: this.props.match.params.id
})
}
render() {
return (
<div>
<h3>{this.props.house.name}</h3>
<ul>
{this.props.house.photos.map((photo, index) => {
return (
<li><img src={`/images/${photo}`} /></li>
)
})
}
</ul>
</div>
)
}
}
export default House;
House component
import React, { Component } from 'react';
class House extends Component {
constructor(props) {
super(props)
this.state = {
houseId: ""
}
}
componentDidMount() {
this.setState({
houseId: this.props.match.params.id
})
}
render() {
return (
<div>
<h3>{this.props.house.name}</h3>
<ul>
{this.props.house.photos.map((photo, index) => {
return (
<li><img src={`/images/${photo}`} /></li>
)
})
}
</ul>
</div>
)
}
}
export default House;
Pass the json data to <House/> component and use the id to display the correct data.
import React, { Component } from 'react';
const data = require('./db.json');
class House extends Component {
constructor(props) {
super(props)
this.state = {
houses: data,
}
}
render() {
const houseId = this.props.match.params.houseId;
return (
<div>
<h3>{this.state.houses[houseId].name}</h3>
<ul>
{this.state.houses[houseId].photos.map((photo, index) => {
return (
<li><img src={`/images/${photo}`} /></li>
)
})
}
</ul>
</div>
)
}
}
export default House;
Create two components, one will be rendered in Houses and one will be render on house/1
// rendered inside Houses
class House extends Component {
render() {
return (
<div>
<h3>{this.props.house.name}</h3>
<ul>
{this.props.house.photos.map((photo, index) => {
return (
<li><img src={`/images/${photo}`} /></li>
)
})
}
</ul>
</div>
)
}
}
HouseInfo, which display data by query parameter
import React, { Component } from 'react';
const data = require('./db.json');
class HouseInfo extends Component {
constructor(props) {
super(props)
this.state = {
houses: data,
}
}
render() {
const id = this.props.match.params.houseId;
const houseId = id >= 1 ? id - 1 : 0;
return (
<div>
<h3>{this.state.houses[houseId].name}</h3>
<ul>
{this.state.houses[houseId].photos.map((photo, index) => {
return (
<li><img src={`/images/${photo}`} /></li>
)
})
}
</ul>
</div>
)
}
}
export default HouseInfo;
Router
import React from 'react';
import { BrowserRouter as Router, Route, NavLink } from 'react-router-dom'
import App from './App'
import Intro from './Intro'
import Houses from './Houses'
import House from './House'
import HouseInfo from './HouseInfo'
export default props => (
<Router>
<Route exact path='/' render={() => <App />} >
<Route exact path='/intro' render={() => <Intro />} />
<Route exact path='/houses' render={() => <Houses />} />
<Route exact path='/houses/:houseId' render={(props) => <HouseInfo {...props} />} />
</Route>
</Router>
)
Entire snippet is right except the thing is that you have wrongly matched the params id,
change the following code in house component
this.setState({
houseId: this.props.match.params.houseId
})
you have to use the same param id ie.,houseId inside the component
using the houseId in the state ie.,(this.state.houseId) in House component, loop through the json data and find the houseId and display the corresponding data.
I don't see what props you are passing to the House component but my guess is not exactly intended ones. Try this:
import { withRouter } from 'react-router-dom';
...
export default withRouter(Houses);
or without withRouter:
<Route exact path='/houses/:houseId' render={House} />
and in your Route your param value is specified as houseId, as it should be in House component:
this.setState({
houseId: this.props.match.params.houseId
})

React Router v4 Nested Routes pass in match with Class Component

I am trying to have a nested route in my application. Where a component is declared with class syntax.
How do I pass match?
As you can see below, I am using the componentDidMount() function to pull in data, so I need to have the member function and I want this component to handle all my logic.
import React, { Component } from 'react';
import ListItem from './ListItem';
import Post from './Post';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
//holds the state for all the components
//passes into listing
//listing will re-direct to proper post using router
export default class Blog extends Component {
constructor(props){
super(props);
this.state = {
articles: [],
content: null
};
}
storeData = (data) => {
const articles = data.map((post, index) => {
return {
key: index,
title: post.title.rendered,
content: post.content.rendered,
excerpt: post.excerpt.rendered,
slug: post.slug
};
});
this.setState(
{
articles: articles
}
);
};
componentDidMount() {
let articles = [];
fetch('https://XXXXX.com/posts/')
.then(data => data.json())
.then(this.storeData).catch(err => console.log(err));
}
render(){
return(
<div className="blog">
<h2> Listings </h2>
{ this.state.articles.map(post => (
<Link to= { `path/${post.slug}` } >
<ListItem
key={post.key}
title={post.title}
content={post.content}
/>
</Link>
))
}
<Route path='posts/:slug' component={Post} />
</div>
);
}
}
Found it out!
If you look below in render, it was saved as a this.props!
However, now it renders the component below rather than replace to another page.
render(){
return(
<div className="blog">
<h2> Listings </h2>
{ this.state.articles.map(post => (
<Link to={ `${this.props.match.url}/${post.slug}` } >
<ListItem
key={post.key}
title={post.title}
content={post.content}
/>
</Link>
))
}
<Route path={ `${this.props.match.path}/:slug` } component={Post} />
</div>
);
}
}

How to pass the state of the page to other React?

I want to know how I can pass a status from one page to another page for if used in the other way.
My first page Body.js (Which I handle the state):
import React from 'react';
import './Body.css';
import axios from 'axios';
import { Link } from "react-router-dom";
import User from './User';
class Body extends React.Component {
constructor (){
super();
this.state ={
employee:[],
employeeCurrent:[],
}
}
componentDidMount(){
axios.get('http://127.0.0.1:3004/employee').then(
response=>this.setState({employee: response.data})
)
}
getName = () => {
const {employee} = this.state;
return employee.map(name=> <Link className='link' to={`/user/${name.name}`}> <div onClick={()=>this.add(name)} key={name.id} className='item'> <img className='img' src={`https://picsum.photos/${name.name}`}></img> <h1 className='name'> {name.name} </h1></div> </Link>)
}
add = (name) => {
const nam = name;
this.state.employeeCurrent.push(nam)
console.log(this.state.employeeCurrent)
}
render(){
return(
<div className='body'>
{this.getName()}
</div>
)
}
}
export default Body;
My second page which I want to get the state called employeeCurrent:
import React from 'react';
import Header from './Header';
import Body from './Body';
class User extends React.Component {
constructor (props){
super(props);
this.props ={
employeeCurrent:[],
}
}
render(){
return(
<div >
{this.props.employeeCurrent}
</div>
)
}
}
export default User;
I'm using the React Router, it looks like this:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import './App.css';
import Home from './Home';
import User from './User';
const AppRouter = () => (
<Router>
<div className='router'>
<Route exact path="/" component={Home}/>
<Route path="/user/:id" component={User}/>
</div>
</Router>
);
export default AppRouter;
My project is:
Home page, where you have users, obtained from the API, all users have attributes (name, age, city and country). Saved in employeeCurrent variable:
What I want is: grab these attributes from the clicked user and play on the user page:
Someone would can help me PLEASE?????
Like I explained earlier, you need to lift the state up:
AppRouter (holds the state and passes it to children)
class AppRouter extends React.Component {
state = {
employeeCurrent: [],
employee: []
};
componentDidMount() {
axios
.get("http://127.0.0.1:3004/employee")
.then(response => this.setState({ employee: response.data }));
}
add = name => {
this.setState(prevState => {
const copy = prevState.employeeCurrent.slice();
copy.push(name);
return {
employeeCurrent: copy
};
});
};
render() {
return (
<Router>
<div className="router">
<Route
exact
path="/"
render={props => (
<Home
{...props}
add={this.add}
employee={this.state.employee}
currentEmployee={this.state.currentEmployee}
/>
)}
/>
<Route
path="/user/:id"
component={props => (
<User
{...props}
employee={this.state.employee}
currentEmployee={this.state.currentEmployee}
/>
)}
/>
</div>
</Router>
);
}
}
Body and User (receive parent state as props together with updater functions):
class Body extends React.Component {
getName = () => {
const { employee, add } = this.props;
return employee.map(name => (
<Link className="link" to={`/user/${name.name}`}>
{" "}
<div onClick={() => add(name)} key={name.id} className="item">
{" "}
<img
className="img"
src={`https://picsum.photos/${name.name}`}
/>{" "}
<h1 className="name"> {name.name} </h1>
</div>{" "}
</Link>
));
};
render() {
return <div className="body">{this.getName()}</div>;
}
}
class User extends React.Component {
render() {
// you will need to map employeeCurrent somehow
return <div>{this.props.employeeCurrent}</div>;
}
}

React js: can I pass data from a component to another component?

I'm new to React and I'm still learning it. I'm doing a personal project with it.
Let me explain my problem:
I have a component called <NewReleases /> where I make an ajax call and take some datas about some movies out on cinemas today. (I take title, poster img, overview etc...) I put all the data in <NewReleases /> state, so that state becomes an object containing an object for each movie and each object contains title poperty, poster property etc... Then I render the component so that it looks like a grid made by movies posters, infos and so on. And this works well.
Then I need a component <Movie /> to take some datas from the state of <NewReleases /> and render them on the HTML. I read other questions where people were having a similar problem, but it was different because they had a children component that was rendered by the parent component. And in that way, people suggested to pass state as props. I can't do that because my <Movie /> component is not rendered by <NewReleases />. <NewReleases /> makes the ajax call and only renders a JSX grid based on the retrieved data.
On index.js I have setup the main page this way:
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import {Home} from './home';
import {Movie} from './movie';
import './css/index.css';
class App extends React.Component {
render() {
return(
<BrowserRouter>
<Switch>
<Route path={'/movie/:movieTitle'} component={Movie} />
<Route path={'/'} component={Home} />
</Switch>
</BrowserRouter>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
(You can't see <NewReleases /> here because it is rendered inside of <Home /> component, which also renders a header and a footer.)
So when I click on a movie rendered by <NewReleases />, the app will let me go on localhost:3000/movie/:movieTitle where :movieTitle is a dynamic way to say the title of the movie (so for example if I click the poster of Star Wars rendered by <NewReleases />, I will go on localhost:3000/movie/StarWars). On that page I want to show detailed infos about that movie. The info are stored in <NewReleases /> state but I can't have access to that state from <Movie /> (I guess).
I hope you got what I want to achieve. I don't know if it is possible. I had an idea: on the <Movie /> I could do another ajax call just for the movie that I want but I think it would be slower and also I don't think it would be a good solution with React.
Note that I'm not using Redux, Flux etc... only React. I want to understand React well before to move to other technologies.
The way you wanna do is more complicated. With parents componentes that's easy to do. And with Redux is much more easy.
But, you wanna this way. I think if you have a state in the app, pass to home a props to set a movie-state and pass this movie-state to component Move, works fine.
The problem is that Route does't pass props. So there is a extensible route you can do. In the code below I get from web this PropsRoute.
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import {Home} from './home';
import {Movie} from './movie';
import './css/index.css';
class App extends React.Component {
constructor() {
super();
this.state = {
movie: {}
}
this.setMovie = this.setMovie.bind(this);
}
setMovie(newMovie) {
this.setState({
movie: newMovie
});
}
render() {
return(
<BrowserRouter>
<Switch>
<PropsRoute path={'/movie/:movieTitle'} movie={this.state.movie} component={Movie} />
<PropsRoute path={'/'} component={Home} setMovie={this.setMovie} />
</Switch>
</BrowserRouter>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
-----
const renderMergedProps = (component, ...rest) => {
const finalProps = Object.assign({}, ...rest);
return (
React.createElement(component, finalProps)
);
}
const PropsRoute = ({ component, ...rest }) => {
return (
<Route {...rest} render={routeProps => {
return renderMergedProps(component, routeProps, rest);
}}/>
);
}
I thinks this can solve your problem.
Here's a quick example. Store your state in a parent component and pass down the state down to your components. This example uses React Router 4, but it shows how you can pass down the setMovie function and movie information via state to one of your child components. https://codepen.io/w7sang/pen/owVrxW?editors=1111
Of course, you'll have to rework this to match your application, but a basic run down would be that your home component should be where you're grabbing your movie information (via AJAX or WS) and then the set function will allow you to store whatever information you need into the parent component which will ultimately allow any child components to access the information you have stored.
const {
BrowserRouter,
Link,
Route,
Switch
} = ReactRouterDOM;
const Router = BrowserRouter;
// App
class App extends React.Component{
constructor(props) {
super(props);
this.state = {
movie: {
title: null,
rating: null
}
};
this.setMovie = this.setMovie.bind(this);
}
setMovie(payload) {
this.setState({
movie: {
title: payload.title,
rating: payload.rating
}
});
}
render(){
return(
<Router>
<div className="container">
<Layout>
<Switch>
<Route path="/select-movie" component={ () => <Home set={this.setMovie} movie={this.state.movie} />} />
<Route path="/movie-info" component={()=><MovieInfo movie={this.state.movie}/>} />
</Switch>
</Layout>
</div>
</Router>
)
}
}
//Layout
const Layout = ({children}) => (
<div>
<header>
<h1>Movie App</h1>
</header>
<nav>
<Link to="/select-movie">Select Movie</Link>
<Link to="/movie-info">Movie Info</Link>
</nav>
<section>
{children}
</section>
</div>
)
//Home Component
const Home = ({set, movie}) => (
<div>
<Movie title="Star Wars VIII: The Last Jedi (2017)" rating={5} set={set} selected={movie} />
<Movie title="Star Wars VII: The Force Awakens (2015)" rating={5} set={set} selected={movie} />
</div>
)
//Movie Component for displaying movies
//User can select the movie
const Movie = ({title, rating, set, selected}) => {
const selectMovie = () => {
set({
title: title,
rating: rating
});
}
return (
<div className={selected.title === title ? 'active' : ''}>
<h1>{title}</h1>
<div>
{Array(rating).fill(1).map(() =>
<span>★</span>
)}
</div>
<button onClick={selectMovie}>Select</button>
</div>
)
}
//Movie Info
//You must select a movie before movie information is shown
const MovieInfo = ({movie}) => {
const {
title,
rating
} = movie;
//No Movie is selected
if ( movie.title === null ) {
return <div>Please Select a Movie</div>
}
//Movie has been selected
return (
<div>
<h1>Selected Movie</h1>
{title}
{Array(rating).fill(1).map(() =>
<span>★</span>
)}
</div>
)
}
ReactDOM.render(<App />,document.getElementById('app'));
nav {
margin: 20px 0;
}
a {
border: 1px solid black;
margin-right: 10px;
padding: 10px;
}
.active {
background: rgba(0,0,0,0.2);
}
<div id="app"></div>
Create a manual object store to get/set the movie information and use it. That's it. Try the following code. That should answer all your questions. Click on any of the new releases, it will redirect to movie info screen with all the details. If you feel bad about the new releases data always refreshing, you may have to create another store, then get/set the data by checking the data exist in store.
Note: Using store and using title(duplicates may occur) in browser URL makes some problems when user refreshes the browser. For that, use id in browser URL, fetch the details using AJAX call and set that details in store.
//store for movie info
const movieInfoStore = {
data: null,
set: function(data) {
this.data = data;
},
clear: function() {
this.data = null;
}
};
class MovieInfo extends React.Component {
componentWillUnmount() {
movieInfoStore.clear();
}
render() {
return (
<div>
<pre>
{movieInfoStore.data && JSON.stringify(movieInfoStore.data)}
</pre>
<button onClick={() => this.props.history.goBack()}>Go Back</button>
</div>
)
}
}
MovieInfo = ReactRouterDOM.withRouter(MovieInfo);
class NewReleases extends React.Component {
handleNewReleaseClick(newRelease) {
movieInfoStore.set(newRelease);
this.props.history.push(`/movie/${newRelease.title}`);
}
render() {
const { data, loading } = this.props;
if(loading) return <b>Loading...</b>;
if(!data || data.length === 0) return null;
return (
<ul>
{
data.map(newRelease => {
return (
<li onClick={() => this.handleNewReleaseClick(newRelease)}>{newRelease.title}</li>
)
})
}
</ul>
)
}
}
NewReleases = ReactRouterDOM.withRouter(NewReleases);
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
newReleases: [],
newReleasesLoading: true
};
}
componentDidMount() {
setTimeout(() => {
this.setState({
newReleases: [{id: 1, title: "Star Wars"}, {id: 2, title: "Avatar"}],
newReleasesLoading: false
});
}, 1000);
}
render() {
const { newReleases, newReleasesLoading } = this.state;
return (
<NewReleases data={newReleases} loading={newReleasesLoading} />
)
}
}
class App extends React.Component {
render() {
const { BrowserRouter, HashRouter, Switch, Route } = ReactRouterDOM;
return (
<HashRouter>
<Switch>
<Route path="/movie/:movieTitle" component={MovieInfo} />
<Route path="/" component={Home} />
</Switch>
</HashRouter>
)
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>
<div id="root"></div>

Categories

Resources