Coder Social home page Coder Social logo

react-router-tutorial's Introduction

React Router Tutorial

Quick lessons for getting up-to-speed with React Router.

See Lesson 1 - Setting Up to get started.

Each lesson is a fully runnable app with all code from the previous lesson, so you can cd lessons/<lesson-folder>, npm install, and then run the appropriate NPM scripts for each lesson from within the lesson folder.

Missing stuff that will come eventually, hopefully ... maybe.

  1. an app that isn't completely pointless
  • egghead.io videos
  • code splitting
  • location state
  • data integration

react-router-tutorial's People

Contributors

andrewcoelho avatar artyomtrityak avatar bmac avatar chrisbolin avatar danthareja avatar derekbtw avatar elrumordelaluz avatar fhelwanger avatar fvgs avatar herobs avatar hexicle avatar jeanlange avatar k4p7 avatar knowbody avatar kristofen avatar levsero avatar luisherranz avatar macrotim avatar mjackson avatar mkulinski avatar mmmaaatttttt avatar mshibl avatar perrin4869 avatar pooyaj avatar ricochet2200 avatar ryanflorence avatar slindemann-eglp avatar timdorr avatar wilfred avatar yarnball avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-router-tutorial's Issues

npm ERR! weird error 127

after run npm start
raise this error
``
tam@tam-G41-M7:~/workspace/react/react-router-tutorial/lessons/01-setting-up$ npm start

[email protected] start /home/tam/workspace/react/react-router-tutorial/lessons/01-setting-up
webpack-dev-server --inline --content-base .

/usr/bin/env: node: No such file or directory
npm ERR! weird error 127
npm WARN This failure might be due to the use of legacy binary "node"
npm WARN For further explanations, please read
/usr/share/doc/nodejs/README.Debian

npm ERR! not ok code 0
``

Failed at the [email protected] start script 'webpack-dev-server --inline --content-base .'.

Hey I'm trying to run the tutorial but the startup script is failing. The error message says:

npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the tutorial package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! webpack-dev-server --inline --content-base .

I'm running npm v3.6.0 and Node v5.6.0, which I believe to be the most current versions. I've attached the full error log. Thanks!

npm-debug.txt

--history-api-fallback doesn't work?

I tried to follow lesson 10 to get clean urls but the server always can't solve /repos even after I added --history-api-fallback and changed the paths in index.html, and restarted the server. Any idea what might go wrong?

Issue in lesson 06

There is an extra line of <IndexRoute component={Home}/> in lesson 6, which prevent the code from compiling. You haven't talked about IndexRoute there yet. :)

Few details to make it perfect :)

Hi folks,

First of all, i think you should add a .babelrc with { presets: ['es2015'] } . Unless I missed something it doesn't work without.

Secondly, onSubmit={this.handleSubmit} should be onSubmit={this.handleSubmit.bind(this)}. otherwise, this will be null in handleSubmit and there will be a null error when trying to get this.context.router

Thanks for the tutorial guys ! It's awesome !

EDIT: I just saw the preset in webpack.config.js but it didn't do the trick apparently for me.

Pretty URLs when the node server that serves your index.html also serves your backend API?

I didn't see anything about this in the documentation.

To get browser history to work the documentation says you need to do the following:

// send all requests to index.html so browserHistory in React Router works
app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, 'index.html'))
})

As I said in the title what if that node server is also serving my backend API? Do I need to have two different servers in production?

Ho to comopose router

Hey, I look a round and I can't find way how to reuse my routes.

Suppose to I have two type of user in my app AdminUser and ComonUser. And must to create two routes.. when I build bundle common user don't need admin parts, is more secure and bundle is lighter.

So I have to Routers; Admin router:

        <Router history={history}>
           <Route component={CommonPage} path="/common">
                ....
            </Route>
            <Route component={AdminPage} path="/admin">
                ....
            </Route>
        </Router>

and Common Router:

        <Router history={history}>
            <Route component={CommonPage} path="/common">
                ....
            </Route>
        </Router>

Ho can I encapsulate Common routes in one Routes? And create some think like this:

        <Router history={history}>
           <CommonRoutes />
            <Route component={AdminPage} path="/admin">
                ....
            </Route>
        </Router>

error "404 - File or directory not found." when publishing on iis

I'm trying to bublish lesson 12 on iis server, but following error appears when I try to open a link in new tab or refresh the page:
404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.
The sample working properly on localhost, my problem is when I copy the bundle.js and the Index.html to the iis server in windows server 2012.
Do you have any sugestion?

06 params.md

Uncaught ReferenceError: Home is not defined

render((
  <Router>
    <Route path="/" component={App}>
      <IndexRoute component={Home}/>
      <Route path="/repos" component={Repos}/>
      {/* add the new route */}
      <Route path="/repos/:userName/:repoName" component={Repo}/>
      <Route path="/about" component={About}/>
    </Route>
  </Router>
), document.getElementById('app'))

How to dynamically load routes matched users role?

Suppose we have 3 roles:

  • admin (users/dictionaries)
  • manager (list of agents/reports and so on..)
  • agent (customers/products/reports)

We need to dynamically load routes sets according to the user role.
As I understand - default routes set must include /, Login and * routes.
Where to right place to load & replace these routes when user is logged under the certain role?
Could you provide some schema code, please

Lesson 11 missing express on dependencies

First of all, thank you so much for this tutorial! It's very well written and easy to follow.

I think that on lesson 11 express could be installed along with if-env and compression.

I didn't make a PR because your commit history is very organized, so I don't know how to proceed.

Make every subject it's own folder

The way the repo is designed is dumb. Any changes require the entire history of the project to be changed.

The idea was you could git checkout to every lesson, but that makes PRs pretty much impossible to accept.

Instead, every lesson should be a folder with a fully runnable app, not a commit in the git history.

No response on port 8080

This probably isn't your issue to solve but you're smart people and it seems to be a barrier for a lot of folks and those who want to run the tutorial. When I run the first lesson I see nothing on localhost:8080. I do however see the app when I hit it using http://127.0.0.1:8080. I have run commands and found nothing else is using that port.
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 17400 getsetbro 27u IPv4 0x3f582051c499540f 0t0 TCP localhost:http-alt (LISTEN)
In fact if I use httpster to host an app there is no issue. One option is to configure webpack to use a different port. So maybe it is the way webpack runs node right now?

There are 54 PR now, why they are still pending?

Firstly, Thank you guys for writing tutorial for it.

When I am working through the lessons, I noticed a few issues and I also see so many PRs are trying to make the document better.

Do you guys need any help ( help to merge PRs)?

06-params What is the best way for populate individual content in Repo.js

Hi, guys

thank you for the tutorial,
and this is the one i been waiting for.

as i mentioned in title,

// ./modules/Repo.js
<div>
        <h2>{this.props.params.repoName}</h2>
        <p>{this.props.params.userName}</p>
        // From this point two repos (react/react-router) should have different content 
</div>

Not sure how and where should i populate content,
in Repo.js or Repos.js? use props?

could anyone give me a hint?
@andrewcoelho

many thanks

Example 13 unused imports

On lesson 13 there is code like:

// modules/routes.js
import React from 'react'
import { Router, Route, browserHistory, IndexRoute } from 'react-router'
import App from './App'
import About from './About'
import Repos from './Repos'
import Repo from './Repo'
import Home from './Home'

module.exports = (
  <Route path="/" component={App}>
    <IndexRoute component={Home}/>
    <Route path="/repos" component={Repos}>
      <Route path="/repos/:userName/:repoName" component={Repo}/>
    </Route>
    <Route path="/about" component={About}/>
  </Route>
)

My question is, why import Router and browserHistory? Is not used anymore inside that module

What is deep paths?

Hi

In Clean URLs with Browser History,

We also need to change our relative paths to absolute paths in index.html since the urls will be at deep paths and the app, if it starts at a deep path, won't be able to find the files.

Can you explain what is deep paths?

Thank you!

real world example

in response to: '1. an app that isn't completely pointless'

what would be a good real world example? ... I've got a team working on a 'real', real world app... involving complex/deep navigation - but doubt its validity in helping others (we're solving horrible, horrible information architecture, react router to the rescue!)

I am curious as to what the world actually wants?

some ideas:

  1. blog, front to back (categories, sections, posts, comments, etc.)
  2. multi-step form/workflow
  3. mobile app
  4. ???

How to disappear url hash in express server

Hi,thanks for reply.

Now I can hide the hash,but when I refresh it will says cannot get.
I saw the tutorial using webpack dev server,than using historyApiFallback:true
but how to do the same in express server?

11 -- Forgot to create server.js file

Now we're ready to create a production server with Express. Here's a first attempt:

There is no step required to save and name the file (e.g server.js).

better to introduce browserHistory instead of hashHistory? (lesson 2)

in lesson 2, the Router history is initially set as hashHistory. later, we are instructed to change this to browserHistory (lesson 10). I was using react-router v2.0.0 and it gave me errors about not having any default history when using hashHistory (let me know if you need more precise wording). it seems better to be introduced to browserHistory.

Lesson 13 - path must be absolute or specify root to res.sendFile

I got this error when setting up server rendering.
It relates to this line in server.js.

app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, 'public', 'index.html'))
})

In the express docs it shows you can pass the filename and an options object specifying the root of the project.

This is the code that got it working for me.

app.get('*', function (req, res) {
  res.sendFile("index.html", { root: path.join(__dirname, 'public') })
})

I'd be happy to make a pull request, though I've never made one before.

Thanks for the tutorial by the way. Very helpful.

npm start error

0 info it worked if it ends with ok
1 verbose cli [ 'C:\Program Files\nodejs\node.exe',
1 verbose cli 'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js',
1 verbose cli 'start' ]
2 info using [email protected]
3 info using [email protected]
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info prestart [email protected]
6 info start [email protected]
7 verbose unsafe-perm in lifecycle true
8 info [email protected] Failed to exec start script
9 verbose stack Error: [email protected] start: webpack-dev-server --hot
9 verbose stack Exit status 3221225501
9 verbose stack at EventEmitter. (C:\Program Files\nodejs\node_modules\npm\lib\utils\lifecycle.js:214:16)
9 verbose stack at emitTwo (events.js:87:13)
9 verbose stack at EventEmitter.emit (events.js:172:7)
9 verbose stack at ChildProcess. (C:\Program Files\nodejs\node_modules\npm\lib\utils\spawn.js:24:14)
9 verbose stack at emitTwo (events.js:87:13)
9 verbose stack at ChildProcess.emit (events.js:172:7)
9 verbose stack at maybeClose (internal/child_process.js:827:16)
9 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
10 verbose pkgid [email protected]
11 verbose cwd D:\git\react-router-tutorial\lessons\01-setting-up
12 error Windows_NT 6.1.7600
13 error argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "start"
14 error node v4.4.0
15 error npm v2.14.20
16 error code ELIFECYCLE
17 error [email protected] start: webpack-dev-server --hot
17 error Exit status 3221225501
18 error Failed at the [email protected] start script 'webpack-dev-server --hot'.
18 error This is most likely a problem with the tutorial package,
18 error not with npm itself.
18 error Tell the author that this fails on your system:
18 error webpack-dev-server --hot
18 error You can get information on how to open an issue for this project with:
18 error npm bugs tutorial
18 error Or if that isn't available, you can get their info via:
18 error
18 error npm owner ls tutorial
18 error There is likely additional logging output above.
19 verbose exit [ 1, true ]

why tips this

error while importing express

Hi, I got an error importing express.
My server.js looks like the one in the repo.

The app works fine but it doesn't render source code on server

`
/server.js:1
(function (exports, require, module, __filename, __dirname) { import * as express from 'express'
^^^^^^

SyntaxError: Unexpected token import
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:148:18)
at node.js:405:3

`

How can I fix this? I'm on Ubuntu

question about 13-server-rendering

Hi,

I was wondering if in server.js, the html constant it says:
...
<script src="/bundle.js"></script>
...
Should this not be:
<script src="/server.bundle.js"></script>
as specified in the webpack.config.server.js

Best regards,

geert

using es6

I'm trying to use es6 classes but I'm getting for example invalid prop 'component' supplied to 'IndexRoute'.

My index.js

render((
  <Router history={hashHistory}>
    <Route path="/" component={App}>
      <IndexRoute component={Talk} />
      <Route path="/admin" component={Admin} />
    </Route>
  </Router>
), document.getElementById('app'));

My App.js

export default class App extends React.Component {
  render() {
    return (
      <div id="app">
        {this.props.children}
      </div>
    );
  }
}

When I replace es6 classes with createComponent, it works.

Am I missing some guide/docs?

Lesson 5 - Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of `App`.

In lesson 5, after adding NavLink components, rendering fails with the following error

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of App.

Render Custom Data

You are going to have a lesson how to render custom data from the server?
Thanks, Anton

lesson 14 broken

Upon download, I execute npm install within /react-router-tutorial/lessons/14-whats-next. After this is installed, I execute npm start and the build begins.

Webpack does it's work and tells me to visit http://localhost:8080 to see the app, but I am greeted with the less-than-friends Cannot GET / response in my browser. There are no build errors, and webpack waits in it's post-build waiting state.

Am I doing something wrong?



sist output:

OS

Darwin
x64

shell

uname: Darwin
echo $SHELL: /bin/zsh
echo $TERM: xterm-256color
echo $TERM_PROGRAM: iTerm.app

node

npm -v: 3.6.0
node --version: v5.7.1

Time created: Mon Apr 18 2016 18:16:23 GMT-0600 (MDT)

single package.json

Whats the reasoning to have individual package.json per lesson? Its just a unnecessary overhead in installing the same modules 14 times.

Doesn't having one for the entire series works better?

Error on npm start?

Afer installing lesson one with no errors, I ran npm start and got the following error:

[email protected] start /Applications/MeteorWebApps/react-router-tutorial/lessons/01-setting-up
webpack-dev-server --inline --content-base .

events.js:141
throw er; // Unhandled 'error' event
^

Error: listen EADDRINUSE 127.0.0.1:8080
at Object.exports._errnoException (util.js:849:11)
at exports._exceptionWithHostPort (util.js:872:20)
at Server._listen2 (net.js:1231:14)
at listen (net.js:1267:10)
at net.js:1376:9
at GetAddrInfoReqWrap.asyncCallback as callback
at GetAddrInfoReqWrap.onlookup as oncomplete

...

Tell the author that this fails on your system:

npm ERR! webpack-dev-server --inline --content-base .

How can I correct this? Thanks in advance for the info.

webpack installed only in devDependencies but used in production

Hi,

First I want to thank you very much for this awesome tutoral.
The quality of this material is great!

I've noticed that in the lesson 12-navigating the package.json file use the npm start command in this way

 "scripts": {
     "start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev",
     "start:dev": "webpack-dev-server --inline --content-base public/ --history-api-fallback",
     "start:prod": "webpack && node server.js"
},

if you run it in development mode it works like a charm but if you start from scratch and you'll do

npm install --production
NODE_ENV=production npm start

you'll get this error

> [email protected] start /Users/..../dev/garbage/react-router-tutorial/lessons/12-navigating
> if-env NODE_ENV=production && npm run start:prod || npm run start:dev


> [email protected] start:prod /Users/..../dev/garbage/react-router-tutorial/lessons/12-navigating
> webpack && node server.js

sh: webpack: command not found

as you can see from the copied package.json here below webpack is installed only in development mode

{
  "name": "tutorial",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "if-env NODE_ENV=production && npm run start:prod || npm run start:dev",
    "start:dev": "webpack-dev-server --inline --content-base public/ --history-api-fallback",
    "start:prod": "webpack && node server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "compression": "^1.6.1",
    "if-env": "^1.0.0",
    "react": "^0.14.7",
    "react-dom": "^0.14.7",
    "react-router": "^2.0.0"
  },
  "devDependencies": {
    "babel-core": "^6.5.1",
    "babel-loader": "^6.2.2",
    "babel-preset-es2015": "^6.5.0",
    "babel-preset-react": "^6.5.0",
    "http-server": "^0.8.5",
    "webpack": "^1.12.13",
    "webpack-dev-server": "^1.14.1"
  }
}

I've discovered this issue publishing an app based on the package.json to heroku.
Maybe a solution like this can help you

Suggestion: onEnter hooks

Hi,
I'd like to submit a suggestion. I feel like an important part of using react router is onEnter hooks which hasn't been explained in much detail. An example with restricted routes would be showcase the onEnter hook in the most practical way.

Add client/server-side rendering of dynamic content?

This is super awesome, thanks for making this.

If there was one thing that would make this tutorial 11/10 imo, it would be fetching dummy data via an AJAX call and figuring out how to make the same data render on the server after refreshing:

  1. User navigates to a specific repo, an ajax call is made to get the number of open issues for example.
  2. But if the user refreshes the page, then the number of issues is already rendered by the server (no need for an ajax call).

That way dynamic content is also crawlable, not just static templates. Of course this is kinda useless in this specific scenario, but would give a good idea for devs on how to server-side render not only static content, but also dynamic.

after 11-productionish-server

I can't make it work for dev environment after applying all the changes from 11th tutorial.
For the production env, it works just fine.

Webpack-dev-server seems up and running but none of changes to modules/*.js files are applying to bundle and refresh the browser.

I just followed instructions on 11th tutorial, read it many times and tried all I can think of.

It happens after making "public" folder and move index.html and index.css file into it.
and add output.path: 'public' to the webpack.config.js file
and add "start:dev": "webpack-dev-server ... --content-base public ... "

It seems index.html tried to load bundle.js file from /public folder not from the one from memory as it usually do.

Nobody experiencing the same?

thanks

06-Params - IndexRoute Is Not Defined

<IndexRoute component={Home}/>

is added in the code snippet a bit too early.

It causes this error:

Uncaught ReferenceError: IndexRoute is not defined

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.