I hope your all staying and are well. I'm having trouble redirecting. The project im building makes a api request on a search and displays the images from Flickr to the DOM. I have NavLinks that take the user to pre loaded images from Flickr such as 'Mountains' and loads a route respectively E.G http://localhost:3000/Mountains. When I make another search I would like the route to go back to the home route. Cheers Guys :)
import React, { Component } from 'react';
import { Redirect} from 'react-router-dom';
import '../index.css';
export default class SearchBar extends Component {
//setting the state of the search text to empty string.
state = {
textInput: ''
}
//this function changes the search text state to value sumbited in the input field
onSearchChange = e => {
this.setState({ textInput: e.target.value });
}
//handleSubmit changes stops the default refresh of the page.
//Then it takes the onSearch property set in the SearchBar route
//After search is then complete it is then reset to empty.
handleSubmit = e => {
e.preventDefault();
this.props.onSearch(this.query.value);
e.currentTarget.reset()
}
//builds out what is to display to the dom.
render () {
return (
<Redirect to="/" />
<div>
<h1>Photo Generator</h1>
<form className="search-form" onSubmit={this.handleSubmit} >
<input type="search"
onChange={this.onSearchChange}
placeholder="Search..."
ref={(input) => this.query = input}
className="search-form"/>
<button type="submit" id="submit" onSubmit={this.handleSubmit} className="search-form button">
<i className="search-form button:hover"></i>
</button>
</form>
</div>
);
}
}
api call from app.js
import React, { Component } from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import axios from 'axios';
import PhotoList from './Components/PhotoList';
import Nav from './Components/Nav';
import NotFound from './Components/NotFound';
import SearchBar from './Components/SearchBar';
import Waterfall from './Components/Waterfall';
import Sunsets from './Components/Sunsets';
import Mountains from './Components/Mountains';
import './index.css';
import apiKey from './config';
//importing all nesssary components to the app.
//setting the set have to a onject with an empty array on pictures
export default class App extends Component {
constructor() {
super();
this.state = {
pictures: [],
sunsets: [],
waterfalls: [],
mountains: [],
loading: true
};
};
//componentDidMount calls when everything on the page as been rendered and makes the API request.
componentDidMount() {
this.performSearch();
}
//using axios to automatically take the data from Flickr and convert it JSON.
//It then sets the pictures array in state to the JSON data from Flickr
// matching the input from the user in the search bar.
//If there is an error with request perfromSearch will catch it.
performSearch = (query = 'Flowers') => {
axios.get(`API KEY`)
.then(response => {
this.setState({
pictures: response.data.photos.photo
});
})
.catch(error => {
console.log('API request failed', error)
})
}
//rendering all of the routes and paths for the projet.
// <Photo/> gets passed the data from the API request so that it can be acessed in the photo component.
render () {
return (
<BrowserRouter>
<div>
<SearchBar onSearch={this.performSearch} />
<Nav />
<Switch>
<Route exact path="/" />
<Route path="/notfound" render={ () => <NotFound /> } />
<Route path="/waterfall" render={ () => <Waterfall data={this.state.waterfalls}/> } />
<Route path="/sunsets" render={ () => <Sunsets data={this.state.sunsets}/> } />
<Route path="/mountains" render={ () => <Mountains data={this.state.mountains} /> } />
</Switch>
<PhotoList data={this.state.pictures}/>
</div>
</BrowserRouter>
);
}
}
I'm having issues accessing a parameter called bookId from the Reader.js component. The parameter is passed down from BookCarouselItem.js using react-router. Reader.js is a connected component.
I'm not sure if that makes a difference, but does react-router work with redux connected components? Or do I need to use something like connected-react-router?
I've tried to refer to similar questions but wasn't able to find a solution, help would be greatly appreciated.
App.js
import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import { routes } from 'constants/index';
import Reader from 'components/reader/Reader'
Class App extends Component {
render() {
return (
<div className='container-fluid main-container'>
<Router>
<div>
<Route
path={'/reader/:bookId'}
component={() => <Reader />}
/>
</div>
</Router>
</div>
);
}
}
export default App;
BookCarouselItem.js
import React from 'react'
import { Link } from 'react-router-dom'
export class BookCarouselItem extends React.Component {
render() {
const { bookThumbnail } = this.props;
const { name, numberOfSections } = bookThumbnail;
const bookId = 0;
return (
<Link className='book-carousel-link' to={`/reader/${bookId}`}>
<div className='book-info-overlay'>
<h5>{name}</h5>
<span>{numberOfSections} Sections</span>
</div>
</Link>
);
}
}
export default BookCarouselItem;
Reader.js
import React from 'react'
import { connect } from 'react-redux'
import { compose } from 'recompose'
export class Reader extends React.Component {
render() {
const { match, pageLevel } = this.props;
console.log(match); // undefined
return (
<div>
<div className='reader-body'>
<Book bookId={match.params.bookId}
pageLevel={pageLevel}
bank={bank}/>
</div>
);
}
}
Const mapStateToProps = (state) => {
return {
metadata: state.book.metadata,
pageLevel: state.book.pageLevel
}
};
const authCondition = (authUser) => !!authUser;
export default compose(
withAuthorization(authCondition),
connect(mapStateToProps, mapDispatchToProps),
)(Reader);
You can just give the component to the component prop and the route props will be passed down to the component automatically.
<Route
path="/reader/:bookId"
component={Reader}
/>
If you want to render something that is not just a component, you have to pass down the route props manually.
<Route
path="/reader/:bookId"
render={props => <Reader {...props} />}
/>
I'm not sure but maybe mapStateToProps rewrite you props so could you please first read this issue
I have looked a lot of questions and answers on the site concerning an issue that I am experiencing.
I have the usual setup with React, React Router and Redux. My top level component is as follows.
// Imports
const reducers = {
main: baseReducer,
form: formReducer,
};
const reducer = combineReducers(reducers);
const store = createStore(
reducer,
applyMiddleware(thunk),
);
store.dispatch(actions.auth.setCurrentUser());
// store.dispatch(actions.api.fetchLineup());
ReactDOM.render(
<Provider store={store}>
<HashRouter>
<App />
</HashRouter>
</Provider>
,
document.getElementById('root')
);
Inside my App.jsx I have the following code:
import React from 'react';
import Main from './Main';
const App = () => (
<div>
<Main />
</div>
);
export default App;
My Main.jsx
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import GroupingContainer from '../containers/Grouping';
import HomeContainer from '../containers/Home';
const Main = () => (
<main>
<Switch>
<Route exact path='/' component={HomeContainer} />
<Route path='/groupings/:id' component={GroupingContainer} />
</Switch>
</main>
);
export default Main;
And finally I have my Grouping.jsx and GroupingContainer.jsx
import React, { Component } from 'react';
function loadGrouping(props, groupingId) {
const grouping = props.main.groupings.find(
(g) => g.id === groupingId
);
if (!grouping) {
props.dispatch(api.fetchGrouping(groupingId));
}
}
class Grouping extends Component {
constructor(props) {
super(props);
loadGrouping(props, props.groupingId);
}
componentWillReceiveProps(nextProps) {
console.log('Next: ', nextProps);
if (nextProps.match && nextProps.match.params.id !== this.props.match.params.id) {
loadGrouping(this.props, nextProps.groupingId);
}
}
render() {
const grouping = this.props.main.groupings.find(
(lg) => lg.id === this.props.groupingId
);
return (
<div>
<h1>{grouping.name}</h1>
</div>
);
}
}
export default Grouping;
GroupingContainer.jsx
import { connect } from 'react-redux';
import Grouping from '../components/Grouping';
const mapStateToProps = (state, ownProps) => {
return {
groupingId: parseInt(ownProps.match.params.id, 10),
...state,
};
};
const mapDispatchToProps = (dispatch) => ({
dispatch,
});
const GroupingContainer = connect(
mapStateToProps,
mapDispatchToProps,
)(Grouping);
export default GroupingContainer;
After the request it fires another action that adds the returned grouping to the store and into an array of groups state.main.groups
I am having 2 problems. When I browse from the root path to one of the groupings, the following flow:
http://localhost:3000 -> http://localhost:3000/#/groupings/19
I receive the message: Uncaught TypeError: Cannot read property 'name' of undefined for a brief second until the API request finishes and populates the {grouping.name} and when I do a complete refresh of the page on a grouping URL http://localhost:3000/#/groupings/19 the application does not load at all and gives them same Uncaught TypeError: Cannot read property 'name' of undefined
I have been using React for around 2 months and have really started using API requests on Component loads. I can not really figure out where to place the API request properly to prevent the view rendering before it has finished and erroring out.
Any help would be appreciated!
Thanks!
Try to change render of Grouping Component like this.
render() {
const grouping = this.props.main.groupings.find(
(lg) => lg.id === this.props.groupingId
);
return (
<div>
<h1>{grouping ? grouping.name : ""}</h1>
</div>
);
}
I am using the last version react-router module, named react-router-dom, that has become the default when developing web applications with React. I want to know how to make a redirection after a POST request. I have been making this code, but after the request, nothing happens. I review on the web, but all the data is about previous versions of the react router, and no with the last update.
Code:
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Redirect } from 'react-router'
import SignUpForm from '../../register/components/SignUpForm';
import styles from './PagesStyles.css';
import axios from 'axios';
import Footer from '../../shared/components/Footer';
class SignUpPage extends React.Component {
constructor(props) {
super(props);
this.state = {
errors: {},
client: {
userclient: '',
clientname: '',
clientbusinessname: '',
password: '',
confirmPassword: ''
}
};
this.processForm = this.processForm.bind(this);
this.changeClient = this.changeClient.bind(this);
}
changeClient(event) {
const field = event.target.name;
const client = this.state.client;
client[field] = event.target.value;
this.setState({
client
});
}
async processForm(event) {
event.preventDefault();
const userclient = this.state.client.userclient;
const clientname = this.state.client.clientname;
const clientbusinessname = this.state.client.clientbusinessname;
const password = this.state.client.password;
const confirmPassword = this.state.client.confirmPassword;
const formData = { userclient, clientname, clientbusinessname, password, confirmPassword };
axios.post('/signup', formData, { headers: {'Accept': 'application/json'} })
.then((response) => {
this.setState({
errors: {}
});
<Redirect to="/"/> // Here, nothings happens
}).catch((error) => {
const errors = error.response.data.errors ? error.response.data.errors : {};
errors.summary = error.response.data.message;
this.setState({
errors
});
});
}
render() {
return (
<div className={styles.section}>
<div className={styles.container}>
<img src={require('./images/lisa_principal_bg.png')} className={styles.fullImageBackground} />
<SignUpForm
onSubmit={this.processForm}
onChange={this.changeClient}
errors={this.state.errors}
client={this.state.client}
/>
<Footer />
</div>
</div>
);
}
}
export default SignUpPage;
You have to use setState to set a property that will render the <Redirect> inside your render() method.
E.g.
class MyComponent extends React.Component {
state = {
redirect: false
}
handleSubmit () {
axios.post(/**/)
.then(() => this.setState({ redirect: true }));
}
render () {
const { redirect } = this.state;
if (redirect) {
return <Redirect to='/somewhere'/>;
}
return <RenderYourForm/>;
}
You can also see an example in the official documentation: https://reacttraining.com/react-router/web/example/auth-workflow
That said, I would suggest you to put the API call inside a service or something. Then you could just use the history object to route programatically. This is how the integration with redux works.
But I guess you have your reasons to do it this way.
Here a small example as response to the title as all mentioned examples are complicated in my opinion as well as the official one.
You should know how to transpile es2015 as well as make your server able to handle the redirect. Here is a snippet for express. More info related to this can be found here.
Make sure to put this below all other routes.
const app = express();
app.use(express.static('distApp'));
/**
* Enable routing with React.
*/
app.get('*', (req, res) => {
res.sendFile(path.resolve('distApp', 'index.html'));
});
This is the .jsx file. Notice how the longest path comes first and get's more general. For the most general routes use the exact attribute.
// Relative imports
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
// Absolute imports
import YourReactComp from './YourReactComp.jsx';
const root = document.getElementById('root');
const MainPage= () => (
<div>Main Page</div>
);
const EditPage= () => (
<div>Edit Page</div>
);
const NoMatch = () => (
<p>No Match</p>
);
const RoutedApp = () => (
<BrowserRouter >
<Switch>
<Route path="/items/:id" component={EditPage} />
<Route exact path="/items" component={MainPage} />
<Route path="/yourReactComp" component={YourReactComp} />
<Route exact path="/" render={() => (<Redirect to="/items" />)} />
<Route path="*" component={NoMatch} />
</Switch>
</BrowserRouter>
);
ReactDOM.render(<RoutedApp />, root);
React Router v5 now allows you to simply redirect using history.push() thanks to the useHistory() hook:
import { useHistory } from "react-router-dom"
function HomeButton() {
let history = useHistory()
function handleClick() {
history.push("/home")
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
)
}
Simply call it inside any function you like.
this.props.history.push('/main');
Try something like this.
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { Redirect } from 'react-router'
import SignUpForm from '../../register/components/SignUpForm';
import styles from './PagesStyles.css';
import axios from 'axios';
import Footer from '../../shared/components/Footer';
class SignUpPage extends React.Component {
constructor(props) {
super(props);
this.state = {
errors: {},
callbackResponse: null,
client: {
userclient: '',
clientname: '',
clientbusinessname: '',
password: '',
confirmPassword: ''
}
};
this.processForm = this.processForm.bind(this);
this.changeClient = this.changeClient.bind(this);
}
changeClient(event) {
const field = event.target.name;
const client = this.state.client;
client[field] = event.target.value;
this.setState({
client
});
}
processForm(event) {
event.preventDefault();
const userclient = this.state.client.userclient;
const clientname = this.state.client.clientname;
const clientbusinessname = this.state.client.clientbusinessname;
const password = this.state.client.password;
const confirmPassword = this.state.client.confirmPassword;
const formData = { userclient, clientname, clientbusinessname, password, confirmPassword };
axios.post('/signup', formData, { headers: {'Accept': 'application/json'} })
.then((response) => {
this.setState({
callbackResponse: {response.data},
});
}).catch((error) => {
const errors = error.response.data.errors ? error.response.data.errors : {};
errors.summary = error.response.data.message;
this.setState({
errors
});
});
}
const renderMe = ()=>{
return(
this.state.callbackResponse
? <SignUpForm
onSubmit={this.processForm}
onChange={this.changeClient}
errors={this.state.errors}
client={this.state.client}
/>
: <Redirect to="/"/>
)}
render() {
return (
<div className={styles.section}>
<div className={styles.container}>
<img src={require('./images/lisa_principal_bg.png')} className={styles.fullImageBackground} />
{renderMe()}
<Footer />
</div>
</div>
);
}
}
export default SignUpPage;
Update for react-router-dom v6, there is a useNavigate hook for condtional redirection and Link component
import { useEffect } from 'react';
import { useNavigate, Link } from 'react-router-dom';
export default function Example(): JSX.Element {
const navigate = useNavigate();
useEffect(() => {
...
if(true) { // conditional redirection
navigate('/not-found', { replace: true });
}
}, []);
return (
<>
...
<Link to="/home"> Home </Link> // relative link navigation to /home
...
</>
);
}
useNavigate
Relative Link Component
Alternatively, you can use withRouter. You can get access to the history object's properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.
import React from "react"
import PropTypes from "prop-types"
import { withRouter } from "react-router"
// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
render() {
const { match, location, history } = this.props
return <div>You are now at {location.pathname}</div>
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)
Or just:
import { withRouter } from 'react-router-dom'
const Button = withRouter(({ history }) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
))
The problem I run into is I have an existing IIS machine. I then deploy a static React app to it. When you use router, the URL that displays is actually virtual, not real. If you hit F5 it goes to IIS, not index.js, and your return will be 404 file not found. How I resolved it was simple. I have a public folder in my react app. In that public folder I created the same folder name as the virtual routing. In this folder, I have an index.html with the following code:
<script>
{
sessionStorage.setItem("redirect", "/ansible/");
location.href = "/";
}
</script>
Now what this does is for this session, I'm adding the "routing" path I want it to go. Then inside my App.js I do this (Note ... is other code but too much to put here for a demo):
import React, { Component } from "react";
import { Route, Link } from "react-router-dom";
import { BrowserRouter as Router } from "react-router-dom";
import { Redirect } from 'react-router';
import Ansible from "./Development/Ansible";
import Code from "./Development/Code";
import Wood from "./WoodWorking";
import "./App.css";
class App extends Component {
render() {
const redirect = sessionStorage.getItem("redirect");
if(redirect) {
sessionStorage.removeItem("redirect");
}
return (
<Router>
{redirect ?<Redirect to={redirect}/> : ""}
<div className="App">
...
<Link to="/">
<li>Home</li>
</Link>
<Link to="/dev">
<li>Development</li>
</Link>
<Link to="/wood">
<li>Wood Working</li>
</Link>
...
<Route
path="/"
exact
render={(props) => (
<Home {...props} />
)}
/>
<Route
path="/dev"
render={(props) => (
<Code {...props} />
)}
/>
<Route
path="/wood"
render={(props) => (
<Wood {...props} />
)}
/>
<Route
path="/ansible/"
exact
render={(props) => (
<Ansible {...props} checked={this.state.checked} />
)}
/>
...
</Router>
);
}
}
export default App;
Actual usage: chizl.com
EDIT: changed from localStorage to sessionStorage. sessionStorage goes away when you close the tab or browser and cannot be read by other tabs in your browser.
NOTE: Answering just the title of the question
Previous Version
<Redirect from="/old-url" to="/new-url" />
Latest version
<Route path="/old-url" element={<Navigate to="/new-url" />} />
In v6 of react-router you can accomplish this using <Navigate/> tag as there is no <Redirect/> Component.
In my case. I was required to maintain the connection to the server between /Home route and /chat route; setting window.location to something would re-render that destroys client-server connection I did this.
<div className="home-container">
{redirect && <Navigate to="/chat"/>}
<div className="home__title">
....
<div className="home__group-list" onClick={handleJoin}>
</div>
const [redirect, doRedirect] = useState(false)
handleJoin changes the state of redirect to true.
you can write a hoc for this purpose and write a method call redirect, here is the code:
import React, {useState} from 'react';
import {Redirect} from "react-router-dom";
const RedirectHoc = (WrappedComponent) => () => {
const [routName, setRoutName] = useState("");
const redirect = (to) => {
setRoutName(to);
};
if (routName) {
return <Redirect to={"/" + routName}/>
}
return (
<>
<WrappedComponent redirect={redirect}/>
</>
);
};
export default RedirectHoc;
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-router-dom": "^4.2.2"
For navigate to another page (About page in my case), I installed prop-types. Then I import it in the corresponding component.And I used this.context.router.history.push('/about').And it gets navigated.
My code is,
import React, { Component } from 'react';
import '../assets/mystyle.css';
import { Redirect } from 'react-router';
import PropTypes from 'prop-types';
export default class Header extends Component {
viewAbout() {
this.context.router.history.push('/about')
}
render() {
return (
<header className="App-header">
<div className="myapp_menu">
<input type="button" value="Home" />
<input type="button" value="Services" />
<input type="button" value="Contact" />
<input type="button" value="About" onClick={() => { this.viewAbout() }} />
</div>
</header>
)
}
}
Header.contextTypes = {
router: PropTypes.object
};
Alternatively, you can use React conditional rendering.
import { Redirect } from "react-router";
import React, { Component } from 'react';
class UserSignup extends Component {
constructor(props) {
super(props);
this.state = {
redirect: false
}
}
render() {
<React.Fragment>
{ this.state.redirect && <Redirect to="/signin" /> } // you will be redirected to signin route
}
</React.Fragment>
}
Hi if you are using react-router v-6.0.0-beta or V6 in This version Redirect Changes to Navigate like this
import { Navigate } from 'react-router-dom'; // like this CORRECT in v6
import { Redirect } from 'react-router-dom'; // like this CORRECT in v5
import { Redirect } from 'react-router-dom'; // like this WRONG in v6
// This will give you error in V6 of react-router and react-router dom
please make sure use both same version in package.json
{
"react-router": "^6.0.0-beta.0", //Like this
"react-router-dom": "^6.0.0-beta.0", // like this
}
this above things only works well in react Router Version 6
The simplest solution to navigate to another component is( Example
navigates to mails component by click on icon):
<MailIcon
onClick={ () => { this.props.history.push('/mails') } }
/>
To navigate to another component you can use this.props.history.push('/main');
import React, { Component, Fragment } from 'react'
class Example extends Component {
redirect() {
this.props.history.push('/main')
}
render() {
return (
<Fragment>
{this.redirect()}
</Fragment>
);
}
}
export default Example
I found that place to put the redirect complent of react-router is in the method render, but if you want to redirect after some validation, by example, the best way to redirect is using the old reliable, window.location.href, i.e.:
evalSuccessResponse(data){
if(data.code===200){
window.location.href = urlOneSignHome;
}else{
//TODO Something
}
}
When you are programming React Native never will need to go outside of the app, and the mechanism to open another app is completely different.
My 'store.js' does the following:
export default function configureStore(initialState = {todos: [], floatBar: {} }) {
return finalCreateStore(rootReducer, initialState)
}
Then in my 'client.js', I have the intialized states, but didn't define 'todos' array, and set up the Router:
let initialState = {
floatBar: {
barStatus: false,
id: 0
}
}
let store = configureStore(initialState)
render(
<div>
<Provider store={store}>
<Router history={hashHistory}>
<Route
path="/"
component={App}
>
<Route
component={FirstPage}
path="firstpage"
/>
<Route
component={NewPage}
path="/newpage/:id"
/>
</Route>
</Router>
</Provider>
</div>,
document.getElementById('app')
)
Then in my 'item.js' component, which is a child of 'FirstPage.js', it gets an object 'todo' and retrieves the '.id', which is an object from the 'todos' object-array (inside the render() return{}), I have the following:
<Link to={`/newpage/${this.props.todo.id}`}>Link1</Link>
Lastly, in my newly linked page, 'NewPage.js', I want to be able to use the same exact 'todo' object in 'item.js', so I can call 'todo.id' and such. How can I do so?
Could anyone show the proper way to do this using redux react-router? Would really appreciate it.
**UPDATE
**NEWEST UPDATE for actions
actions.js has all of my action creators inside:
import * as actions from '../redux/actions'
class NewPage extends Component{
handleCommentChange(){
this.props.actions.updateComment()
}
render(){
return()
}
}
function mapDispatchToProps(dispatch){
return{
actions: bindActionCreators(actions, dispatch)
}
}
export default connect(
mapDispatchToProps
)(NewPage);
You can access to "todo id" from props.params.id . Also you can access to props.params of NewPage through "ownProps" in "mapStateToProps"
import {connect} from "react-redux";
import React, { Component } from 'react'
import { Divider } from 'material-ui'
const styles = {
title:{
color: 'white',
textAlign: 'left',
marginLeft: 30
}
}
class NewPage extends Component{
render(){
return(
<div>
<div style={styles.title}>
<font size="4">
{this.props.todo.title}
</font>
</div>
<Divider style={{backgroundColor:'#282828'}}/>
<p style={{color: 'white'}}>{this.props.todo.detail}</p>
</div>
)
}
}
const mapStateToProps=(state, ownProps)=>{
let todo = state.todos.filter(todo=>todo.id==ownProps.params.id);
return{
todo:todo[0]
}};
export default connect(mapStateToProps)(NewPage);
Another approach, especially useful for dynamic props, is to clone the child component that gets injected as
props by React Router, which gives you the opportunity to pass additional props in the process.
example
class Repos extends Component {
constructor(){...}
componentDidMount(){...}
render() {
let repos = this.state.repositories.map((repo) => (
<li key={repo.id}>
<Link to={"/repos/details/"+repo.name}>{repo.name}</Link>
</li>
));
let child = this.props.children && React.cloneElement(this.props.children,
{ repositories: this.state.repositories }
);
return (
<div>
<h1>Github Repos</h1>
<ul>
{repos}
</ul>
{child}
</div>
);
}
}
////////////////////////////
class RepoDetails extends Component {
renderRepository() {
let repository = this.props.repositories.find((repo)=>repo.name === this.props.params.
repo_name);
let stars = [];
for (var i = 0; i < repository.stargazers_count; i++) {
stars.push('');
}
return(
<div>
<h2>{repository.name}</h2>
<p>{repository.description}</p>
<span>{stars}</span>
</div>
);
}
render() {
if(this.props.repositories.length > 0 ){
return this.renderRepository();
} else {
return <h4>Loading...</h4>;
}
}
}