Coder Social home page Coder Social logo

reactjs / react-tutorial Goto Github PK

View Code? Open in Web Editor NEW
3.3K 3.3K 2.1K 1.01 MB

Code from the React tutorial.

Home Page: http://facebook.github.io/react/docs/tutorial.html

License: Other

CSS 4.17% Go 18.97% JavaScript 36.49% PHP 10.25% Python 8.43% Ruby 8.91% HTML 5.07% Perl 7.71%

react-tutorial's Introduction

Deploy

React Tutorial

This is the React comment box example from the React tutorial.

To use

There are several simple server implementations included. They all serve static files from public/ and handle requests to /api/comments to fetch or add data. Start a server with one of the following:

Node

npm install
node server.js

Python

pip install -r requirements.txt
python server.py

Ruby

ruby server.rb

PHP

php server.php

Go

go run server.go

Perl

cpan Mojolicious
perl server.pl

And visit http://localhost:3000/. Try opening multiple tabs!

Changing the port

You can change the port number by setting the $PORT environment variable before invoking any of the scripts above, e.g.,

PORT=3001 node server.js

react-tutorial's People

Contributors

acme avatar andymathys avatar chenglou avatar chenxsan avatar darthneel avatar dbunker avatar fokko avatar foohyfooh avatar high5 avatar jimfb avatar jisupark avatar leonidez avatar martellaj avatar maxbittker avatar mecampbellsoup avatar michaeldhopkins avatar michaelrp avatar msukmanowsky avatar mttrs avatar psibi avatar robatron avatar saiyam-gambhir-zz avatar slava-sh avatar sophiebits avatar sthodup1 avatar victorleungtw avatar vmaudgalya avatar xyproto avatar yangshun avatar zpao 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-tutorial's Issues

Data output with order by created_at

Hi, guys! I have a question.
I have the dynamically list of posts. When i click "Post" button, new post created at the bottom of the list, but i want to see new post at the top of list. How can I do this?

Couldn't start the server using nodejs

The error is:

module.js:338
throw err;
^
Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:278:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object. (/Users/tianhao/Project/ReactProject/react-tutorial/server.js:15:15)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)

tutorial8.js

// tutorial8.js
var data = [
  {author: "Pete Hunt", text: "This is one comment"},
  {author: "Jordan Walke", text: "This is *another* comment"}
];

do not work

but

// tutorial8.js
var data = [
  {"author": "Pete Hunt", "text": "This is one comment"},
  {"author": "Jordan Walke", "text": "This is *another* comment"}
];

work correctly

This is a minor issue:

I just was playing with the tutorial on node.js.

When it came right out of the box at least for me (I might be some edge case), the comments showed up with ,commas on either side of the comment body( or text), <like here. To fix this I adjusted rawMarkup to apply the marked function on this.props.children[1].toString() rather than this.props.children.toString();

var Comment = React.createClass({
    render: function () {
        console.log(this.props.children[1]);
        var rawMarkup = marked(this.props.children[1].toString(), {
            sanitize: true
        });
    return ( 
        <div className="comment">
            <h2 className="commentAuthor"> {this.props.author}</h2> 
            <span dangerouslySetInnerHTML = {{__html: rawMarkup }}/>
        </div>
        );
    }
 });

I also made a few adjustments to the server (switching res.setHeader( application/json)+ res.send(data) to just res.json(data), but by reverting back and forth it didn't seem to make a difference.

app.use(bodyParser.json({ extended: false }));

app.get('/comments.json', function(req, res) {
  fs.readFile('comments.json', function(err, data) {
    //res.setHeader('Content-Type', 'application/json');
    console.log(data);
    res.json(data);
  });
});

Race condition in refresh code

If you POST a new comment at the same time you poll, the optimistic GUI update occurs, then if the poll returns before the POST, it'll cause the comment on the GUI to disappear again until the POST returns. So you get a little flash before the comment appears permanently.

Comment data array introduced in the Updating state section

I'm submitting this issue as a reference point for anyone else who may experience the same.

As a novice js programmer new to React I found the comment data array introduced in the Updating state section (see screenshot below) confusing at first. There is no text in the tutorial about where this data should be located. It seemed intuitive that I was supposed to include this data somewhere, but I couldn't tell where it should go (inside a React component? Independent from React components in the way that var data was introduced earlier in the tutorial? As a separate file?).

screen shot 2015-11-24 at 09 04 04

The answer is you don't do anything with the comment data array. The data is already found in the tutorial files as /comments.json. The json file was called into the system at an earlier step when you updated the ReactDOM.render to <CommentBox url="/api/comments" />,.

This is configured in the server file. If you're using the js server, this happens at:

  1. https://github.com/reactjs/react-tutorial/blob/master/server.js#L19, then
  2. https://github.com/reactjs/react-tutorial/blob/master/server.js#L27

Also, it appears that the tutorial didn't always work like this. You can read PR #79 for the history of the comments file being used in this way (current at least for the end of year 2015).

XSS in tutorial example

Hi,

There is a pretty obvious XSS in the example code -- a comment such as:

 <img onmouseover="alert(1);" src="http://www.frikipedia.es/images/thumb/d/d5/Asdsa-asdas.jpg/300px-Asdsa-asdas.jpg">

Will trigger JS exec.

There are some XSS "signposts" in the tutorial (Quote: "Remember: by using this feature you're relying on Showdown to be secure."), but ultimately this isn't setting a great example for new react developers.

Thanks - Blair.

SecurityError: The operation is insecure browser.js

I have copy all of the file of the tutorial but I have an error and I can't find it
SecurityError: The operation is insecure ....indexOf(k) === -1 && has.call(window, k) && window[k] !== null && typeof window... browser.js (ligne 43387)

PS: I am behind a proxy

not compatible with ie 11 in some scenarios

run https://github.com/reactjs/react-tutorial in Chrome and Firefox, it works as expected.

But in IE 11, after post a new comment, the new comment will flash for a second at the bottom, then it disappears. Refresh the browser window, the new comment does not show.

When close all IE windows, and open a new process of IE, the new comment will show.

Launch developer tools will also show the new comment.

Also similar issue repro in https://github.com/i-like-robots/react-tube-tracker. So it's not specific to the code.

Repro in different machines. So it's not specific to machine configuration.

Opened a question in stackoverflow.com: http://stackoverflow.com/questions/28723826/reactjs-is-not-compatible-with-ie-11-in-some-scenarios

Create simple server for collection of languages

Instead of forcing Node on people from the beginning, it would be great to make this a place that's easy for anybody to jump into.

  • JS/Node
  • Python
  • Ruby
  • Java?
  • PHP

I think it shuold be as easy as this and they should all work identically without dependencies if possible (right now node requires npm install, possible to make it work without by maybe not reasonable)

node server.js
python server.py
ruby server.rb
php server.php

POST not updating comments.json on Apache server

I'm using a local dev environment (Vagrant box with CentOS + Apache) to run the tutorial, and the POST isn't updating file comments.json.
If running the tutorial this way, is this not possible, or is there a server script that needs to be added to update file comments.json?
Thanks!

Prohibitive license conuterproductive to educational materials?

Hi,

thank you so much for the fine tutorial and example code.

Unfortunately I'm a more than a little concerned with the license text: "The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted.". (a8c9f89)

This means that using or substantially reproducing your examples and code in production will leave users in breach of copyright! Personally I strongly believe that the best license for tutorial example code is a dual CC0/public domain (where applicable) and a liberal license like BSD/MIT/APL, possibly LGPL (but for example code, I think "no strings attached" is more constructive).

I find it hard to believe that the intent is for people to have to work around reusing the knowledge presented in the repository when working with react?

Is there any chance the license could be changed? Then I wouldn't have to be afraid to recommend the article to people that work on production systems...

Tutorial 3 - Runtime Errors

When trying to use the CommentList and CommentForm I receive these errors.

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 CommentBox.

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of CommentBox.

  var CommentBox = React.createClass({
    render: function() {
      return (
        <div className="commentBox">
          <h1>Comments</h1>
          <CommentList />
          <CommentForm />
        </div>
      );
    }
  });
  ReactDOM.render(
    <CommentBox />,
    document.getElementById('content')
  );

Any help is greatly appreciated.

Fails to roll back optimistic update after error

Shouldn't we do something like this.setState({data: comments}); before logging the error to the console on line 58 of example.js? Otherwise comments.json and current state will be out of sync after an error.

server.rb does not reload comments.json

The tutorial states that the file _comments.json will be reloaded with each request for '/comments.json'. However, server.rb only loads this file once before webbrick is started. Moving the loading and parsing of _comments.js into the block server.mount_proc '/comments.json' solves the problem.

Stored XSS in Mark Down

The markdown library (marked) used in this demo does not properly handle HTML entities (even with the sanitize option set to true). This leads to a stored XSS in this demo.

The marked project also appears to be abandoned. I suggest using something else in the demo. I know this is not intended to be production code, but people will follow this as an example. You can also see this in action on the main https://facebook.github.io/react/ page under "A Component Using External Plugins" as a "self xss"

POC:

Run the project and submit a comment with the following markdown:

[XSS](javascript&#58document;alert&#40;1&#41;)

References:

The pull request I opened to them (a long time ago):
markedjs/marked#592

A full writeup on the actual issue:
https://snyk.io/blog/marked-xss-vulnerability/

The Node Security Advisory:
https://nodesecurity.io/advisories/101

As well as RetireJS:
http://retirejs.github.io/retire.js/

Update for 0.14

@spicyj made some changes in the React repo to use ReactDOM. We should do that here too as well as bump versions to 0.14 once we ship.

Update script sources on tutorial page

Hi there,
Would it be possible to update the tutorial to the cloudflare script sources like in the repo?
Perhaps the tutorial could be revised as a whole for consistency with these example files.
Cheers and thanks~

License

Could you add a license/Unlicense to this tutorial code? I know the code is not really meant for anything other than practice, but supposing I were to use parts as boilerplate for a simple project it would be nice to have.

does not seem to work

I tried this code and I can never see the comment just added. Is it supposed to work as written to display newly added comment?

Error undefined

I am trying to walk through the tutorial and I am getting an error on section "tutorial3.js" when you add the comment list and comment form to the comment box.

I downloaded the starter kit and I am using the "Offline Transform" method to compile the jsx to plain javascript.

I uploaded the files to a repo.
http://mikecasas.github.io/react-tutorial

Better visualisation of component hierarchy?

I went through the tutorial recently and found it great!

One thing that I think can be improved for beginners is visualization of component hierarchy. It is very well described and visualized in Step-1 of Thinking in React.

So I went ahead and added a little CSS to make it clear. Please see screenshots below. Do you think something like this will add value? If so, I would love to improve it a bit and submit a PR.

Thanks :)

Before:
screen shot 2016-07-07 at 8 15 37 pm

After:
screen shot 2016-07-07 at 8 08 54 pm

started error

node_modules\path-to-regexp\index.js:63
path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?'))
TypeError: Cannot read property 'length' of undefined

Error 404 comments.json Not found

I downloaded react-tutorial then tried to run it using python -m SimpleHTTPServer or http-server but got this error. Note that I've already run npm install and node server.js

http-server

"GET /comments.json?_=1432976000368" Error (404): "Not found"

python -m SimpleHTTPServer

"GET /comments.json?_=1432976065093 HTTP/1.1" 404 -

I've tried in both root and public folder.

Uncaught SyntaxError: embedded: Unexpected token (18:8)

Using Chrome v50.0.2661.102 (64-bit), I installed the server using npm.

I'm on the first step of the tutorial, here's what I have:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>React Tutorial</title>
    <!-- Not present in the tutorial. Just for basic styling. -->
    <link rel="stylesheet" href="css/base.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.16/browser.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.6.2/remarkable.min.js"></script>
  </head>
  <body>

    <div id="content"></div>

    <script type="text/babel">

      var CommentBox = React.createClass({
        render: function() {
          return (
            <div className="commentBox">
              <h1>Comments</h1>
              <CommentList />
              <CommentForm />
              Hello, world! I am a CommentBox.
            </div>
          );
        }
      });

      ReactDOM.render(
        <CommentBox />
        document.getElementById('content')
      );

    </script>
  </body>
</html>

This produces the following error in the console:

browser.js:2027 Uncaught SyntaxError: embedded: Unexpected token (19:8)pp.raise @
browser.js:2027pp.unexpected @ browser.js:2596pp.expect @ browser.js:2590pp.parseExprList @
browser.js:1627pp.parseSubscripts @ browser.js:1124pp.parseSubscripts @ 
browser.js:1113pp.parseExprSubscripts @ browser.js:1099pp.parseMaybeUnary @ 
browser.js:1079pp.parseExprOps @ browser.js:1035pp.parseMaybeConditional @ 
browser.js:1018pp.parseMaybeAssign @ browser.js:986pp.parseExpression @ 
browser.js:961pp.parseStatement @ browser.js:2822(anonymous function) @ 
browser.js:657pp.parseTopLevel @ browser.js:2723parse @ browser.js:1921exports.default @ 
browser.js:8217parse @ browser.js:9097parseCode @ browser.js:9182(anonymous function) @ 
browser.js:13132wrap @ browser.js:9146transform @ browser.js:13130transform.run @ 
browser.js:4613exec @ browser.js:4649runScripts @ browser.js:4680

Simple web servers don't reload json file

Right before the Adding new comments section, the user is encouraged to change the comments.json file and and wait 2 seconds for the change to be picked up. The web servers won't reload the file without a restart.

server.js problem

I don't know if I got something wrong here. but it seems like the handler for "comment.js" in Nodejs version of server code never been executed, instead, any GET request like "http://localhost:3000/comments.js" is treated as static file, just bypass the handler associated with router.

npmcdn can't find react js file

NPMCDN can't find the version of the React JS file that is linked to in index.html.

I replaced the offending line with

<script src="https://npmcdn.com/react/dist/react.min.js"></script>

which downloads the latest version.

I think this router should be app.get('/comments')

app.get('/comments.json', function(req, res) {
  fs.readFile('comments.json', function(err, data) {
    res.setHeader('Content-Type', 'application/json');
    res.send(data);
  });
});

because when I use router file index.js default in Express demo,it is still work even if there is
no these code.
it seems need to delete the .json,and the html/jade file should be
<CommentBox url="/comments" pollInterval={20000} />

Convert from React.createClass to ES6 classes

Given React is moving syntactically towards native javascript/ES6. It's time to change createClass to ES6 class.

reactive-native already follows ES6 classes in their source and tutorial.

Tutorial comment.json not synchronised with server sources

In the tutorial these parts point to a path not exactly the same than the server are providing:
https://facebook.github.io/react/docs/tutorial.html#fetching-from-the-server

<CommentBox url="/api/comments" />,

And https://facebook.github.io/react/docs/tutorial.html#updating-state

<CommentBox url="/api/comments" pollInterval={2000} />,

Where it should be url="/comments.json" like in the repository
Issue really similar to #67 facebook/react#4673 #78

Warning: React.render is deprecated.

代码运行有这个报错:Warning: React.render is deprecated. Please use ReactDOM.render from require('react-dom') instead. 不影响实际结果,想了解下,这是否表示 React.render已经被废弃了,改成了方法ReactDOM.render?

Restful API...

Hi,
I think it might be better to change the tutorial server urls to be Restful - e.g. instead of /comments.json => /comments

Remove comments.json from source control

When playing with a local version of the demo, new comments modify comments.json, which are detected by git, and dirties the current index.

Could we add comments.json to the .gitignore, check if it exists when the app starts, and if not, create it with the existing content below?

[
    {
        "author": "Pete Hunt",
        "text": "Hey there!"
    }
]

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.