Skip to content

Instantly share code, notes, and snippets.

@varren
Created August 15, 2017 16:29
Show Gist options
  • Save varren/b8d09b6e76d1c683d68784e63296182f to your computer and use it in GitHub Desktop.
Save varren/b8d09b6e76d1c683d68784e63296182f to your computer and use it in GitHub Desktop.
react-router v4 navigation from code programmatically
import React, {Component} from 'react';
import {BrowserRouter, Route, Link} from 'react-router-dom'
/**
* localhost:8080/nature or
* localhost:8080/building
* |---------------|
* | |
* | List of |
* | articles |
* | |
* | |
* | |
* |---------------|
* localhost:8080/nature/1 or
* localhost:8080/building/1
* |---------------|
* | |
* | List of |
* | articles |
* | |
* | article №1 |
* | |
* | |
* |---------------|
*
**/
const db = {
"nature": {
"1": "nature article 1",
"2": "nature article 2"
},
"building": {
"1": "building article 1",
"2": "building article 2"
},
};
var centeredDivStyle = {
"position": "fixed",
"top": "50%",
"left": "50%",
"margin-top": "-150px",
"margin-left": "-150px",
"height": "300px",
"width": "300px"
};
class App extends Component {
render() {
let listOfTopics = Object.keys(db).map(key =>
<div key={key}><Link to={"/" + key}>{key}</Link></div>
);
return (
<BrowserRouter>
<div style={centeredDivStyle}>
<div>Select Topic:</div>
<div>{listOfTopics}</div>
<br/>
<Route path={'/:topic'} component={Topics}/><br/>
<Route path={'/:topic/:article'} component={Article}/>
</div>
</BrowserRouter>
);
}
}
class Topics extends Component {
render() {
let selectedTopic = this.props.match.params.topic;
let listOfArticles = Object.keys(db[selectedTopic]).map(key => {
let url = "/" + selectedTopic + "/" + key;
return <div key={key}>
<a href={url} onClick={() => this.props.history.push(url)}>{key}</a>
{/* Same as <Link to={url}>{key}</Link>*/}
</div>
});
return <div>Selected Topic: {selectedTopic} <br/> {listOfArticles} </div>
}
}
class Article extends Component {
render() {
let topic = this.props.match.params.topic;
let article = this.props.match.params.article;
return <div>Selected Article: {db[topic][article]}</div>;
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment