MediaWiki API result

This is the HTML representation of the JSON format. HTML is good for debugging, but is unsuitable for application use.

Specify the format parameter to change the output format. To see the non-HTML representation of the JSON format, set format=json.

See the complete documentation, or the API help for more information.

{
    "batchcomplete": "",
    "continue": {
        "gapcontinue": "Ruby_on_Rails",
        "continue": "gapcontinue||"
    },
    "query": {
        "pages": {
            "651": {
                "pageid": 651,
                "ns": 0,
                "title": "React",
                "revisions": [
                    {
                        "contentformat": "text/x-wiki",
                        "contentmodel": "wikitext",
                        "*": "https://react.dev/\n\n\n<br />\nReact (also known as React.js or ReactJS) is a JavaScript library (not a Framework) for building user interfaces. It is maintained by Facebook.\n\nReact can be used as a base in the development of single-page or mobile applications.\n\nReact allows us to build component-based user interfaces (UI). A component is a self-contained standalone piece of functionality. For example, a drop-down menu or a collapsible panel can be implemented as a React component.\n\n\nTo understand what is React, we can said that, in general, React generates ''html'' using ''JS'' or ''TypeScript''. You can choose if you want to do generate the html in the client site or in the server site. This course is focused about how to do it in the client site. In the sever site is more complicate and it is done just in some particular case.\n\n\nWe'll be follwing the official documentation of React:\n\nhttps://reactjs.org/docs/getting-started.html#learn-react\n* If you prefer to learn by doing, start with our practical tutorial: https://reactjs.org/tutorial/tutorial.html\n* If you prefer to learn concepts step by step, start with our guide to main concepts: https://reactjs.org/docs/hello-world.html\n\nIt is recommended to start by the guide to main concepts.\n\n\n* To test codes (html, css, JS) we can use this web site: Para probar c\u00f3digos: https://codepen.io/pen\n\n\n<br />\n==Ejemplos comparacion con JS==\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\nimport {\n    IonButtons,\n    IonCard,\n    IonCardContent,\n    IonCardHeader,\n    IonCardSubtitle,\n    IonCardTitle,\n    IonContent,\n    IonHeader,\n    IonIcon,\n    IonItem,\n    IonLabel,\n    IonList,\n    IonListHeader,\n    IonMenuButton,\n    IonPage,\n    IonTitle,\n    IonToolbar\n    } from '@ionic/react';\n\n\ninterface Home2Props{\n\n}\n\ninterface Home2State{\n    result: string;\n    num1: string;\n    num2: string\n}\n\nexport default class Home2 extends React.Component<Home2Props, Home2State> {\n    public constructor(props: Home2Props){\n        super(props)\n        this.state = {\n            result: \"\",\n            num1: \"\",\n            num2: \"\"\n        };\n    }\n    public render(){\n        return (\n            <IonPage>\n                <div>\n                    Hola\n                    <input\n                        type=\"string\"\n                        value={this.state.num1}\n                        onChange={e => this._onTodoChangeInput1(e.target.value)}\n                    />\n                    <input\n                        type=\"string\"\n                        value={this.state.num2}\n                        onChange={e => this._onTodoChangeInput2(e.target.value)}\n                    />   \n                    <button onClick={() => this._add()}>Add</button>\n                    <div> {this.state.result} </div>\n                </div>\n            </IonPage>\n        );\n    }\n    private _add(){\n        // The \"+\" before the variable conver is to convert from string to number\n        const resultado = +this.state.num1  +  +this.state.num2;\n        this.setState({result: resultado.toString()})\n    }\n    private _onTodoChangeInput1(value: string){\n        this.setState({\n             num1: value\n        });\n    }\n    private _onTodoChangeInput2(value: string){\n        this.setState({\n             num2: value\n        });\n    }\n}\n\nasync function getData(){\n    const response = await fetch(\"http://www.apilayer.net/api/live?access_key=cb51ac5d62bd1e6713b4b6c6e015d6b6\");\n    const json = await response.json();\n    // return json;\n    return json.quotes.USDUUR;\n}\n</syntaxhighlight>\n\n\n<br />\n==Deploy a Node-Express and React Application==\nWe have used '''PM2''' as an application manager in order to keep our app running after we log out of the server: \n* https://pm2.keymetrics.io/docs/usage/process-management/\n* https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-14-04\n\n\nInstall PM2:\n sudo npm install pm2 -g\n\n\nStart the app:\n pm2 start app.js\n pm2 start app.js --name \"my-api\"  # Si queremos darle un nombre al proceso pm2\n\n\nThe display the list of applications currently managed by PM2:\n pm2 list\n\n\nTo get more details about an app currently manged by PM2:\n pm2 show <id|name>  # See the id display by the \u00abpm2 list\u00bb command\n\n\nStop an application with this command (specify the PM2 App name or id):\n pm2 stop <id|name>  # No elimina la app de la lista de procesos pmw, only stops it\n\n\nRestart an application with this command (specify the PM2 App name or id):\n pm2 restart <id|name>\n\nsudo npm run build\nNow you want to delete the app from the PM2 process list. You just have to enter the following commands:\n pm2 delete <id|name>\n\n\n<br />\n===Node===\nTo deploy the node application solo tuve que  ejecutar: \n pm2 start build/index.js --name \"twitterclone-backend\"\n\nAhora, '''no me acuerdo''' si tuve primero que buid la JS application (el directorio build) siguiendo algunos de los pasos en este post: \nhttps://medium.com/javascript-in-plain-english/typescript-with-node-and-express-js-why-when-and-how-eb6bc73edd5d\n\nLo que si he constatado la \u00faltima vez que estuve revisando es que la siguiente parte de dicho post:\n\n\u00abTo run the server in production mode:\n npm run prod\u00bb\n.. no funciona y no fue as\u00ed que complet\u00e9 el deployment en production. En el \u00abpackage.json\u00bb se encuentran los script propuestos por este post pare ejecutar el \u00abnpm rn prod\u00bb; pero me imagino que lo hice solo para probar pero no est\u00e1 funcionando.\n\n\n<br />\n===React===\nhttps://facebook.github.io/create-react-app/docs/production-build\n\nhttps://facebook.github.io/create-react-app/docs/deployment\n\n\nhttps://medium.com/@seanconrad_25426/setting-up-a-create-react-app-with-pm2-and-nginx-on-digitalocean-1fd9c060ac1f\n\n\nTo deploy the react app I did:\n sudo npm run build\n pm2 start node_modules/react-scripts/scripts/start.js --name \"twitterclone-frontend\"\n\n\n<br />\n\n==JSFiddle==\nhttps://jsfiddle.net/\n\nJSFiddle is an online community for testing and showcasing user-created and collaborational HTML, CSS and JavaScript code snippets, known as 'fiddles'. It allows for simulated AJAX calls. \n\n\n<br />\n==Execute some JS commands from the Web Browser console==\nYou can use JS to access and modify the ''html'' and the ''css''. You can, for example, create a new ''html'' element in the DOM.\n\nLet's see how that works. From the Web Browser console, you can display the structure of the page and make changes on it. For example, you can display the body of the web page by executing:\n\n document.body\n\n\nYou can make changes in the background color with:\n\n document.body.bgcolor = \"red\"\n\n\n<br />\n==Single Web Application==\nWe said that we are creating a single web page App because what the server send to the client is only one page, which is that index.html page. Then, the Reanc Application can have as many pages as we want, but they are all generated in the client site. \n\n\n<br />\n\n==The main characteristics of React==\n* '''SimplicityReact:''' can seem very different from other libraries at first glance but its API is minimaland its programming model is actually quite simple. As a result, learning React or investigating the causes of an issue can be relatively simple tasks.\n\n* '''Component-based:''' We are going to learn more component-based UI development in the following section.\n\n* '''JavaScript APIs over custom APIs:''' The React API tries to use standard JavaScript APIs instead of custom APIs. For example, in React we can implement a loop while rendering elements using theJavaScript ''map'' function, instead of a custom API such as the ''ng-repeat'' API in Angular.\n\n* '''Highly influenced by functional programming principles:''' React is highly influenced by functional programming. The implications of these influences are very noticeable in many of the React API and design principles. The following are some of the main characteristics of React that can be considered as a direct result of its Functional Programming roots:\n\n:* '''Immutability:''' React encourages us to use immutable objects and avoid state mutations.\n\n:* '''Stateless:''' In React we have to worry a lot about the application's state. React encourages us to try to avoid it and to push it to the boundaries of our system.\n\n:* '''Declarative over imperative:''' React encourages a declarative programming style over an imperative programming style.\n\n\n<br />\n===Component-based UI development===\nReact allows us to implement (SPAs) using a UI programming model known as component-based UI development. The main building block in a component-based UI development library or framework is a '''web component'''. A web component is a piece of the UI that is isolated, and self-contained. A web component encapsulates the HTML, CSS, and JavaScript.\n\nWhen we build a component-based UI, we start by implementing the most basic web components such as inputs and buttons. We can call these components primitives. We then combine primitive components to build more sophisticated components and eventually we compose multiple advanced components to create the pages in our web application. However, the pages themselves can also be implemented as web components.\n\n\n<br />\n===Virtual DOM===\nReact uses a pattern known as virtual DOM (VDOM) (DOM: Document Object Model) where a virtual representation of a UI is kept in memory and synced with the real DOM by a library such as '''''ReactDOM'''''. The synchronization process is called reconciliation.\n\nThe virtual DOM allows us to update the DOM in a declarative way, so we don\u2019t need to worry about how React updates the DOM internally. React can figure out how to efficiently update the DOM from the previous HTML tree to the next version in a very efficient way. You may have heard about '''''React Fiber''''' is the new reconciliation engine in React 16. Its maingoal is to enable incremental rendering of the virtual DOM.\n\nIt is important not to confuse the virtual DOM with the shadow DOM. The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components. The virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.\n\n\n<br />\n==The main benefits of React==\n* '''Simplier applications:''' The React programming model can simplify the development of complex web applications. In particular, when compared against other technologies that don't use a component-based web development model.\n\n* '''Fast user interfaces:''' The React rendering engine is very fasts and efficient. Using React can helpus to achieve an outstanding web application performance.\n\n* '''Re-usability:''' Web components are highly reusable by nature. They provide an abstraction for apiece of UI functionality so it can be re-used.\n\n* '''Test ability:''' React is highly influenced by some functional programming ideas. As a result, React encourages the implementation of stateless components and immutable properties. We will learn more about these principles later, but for now, we can say that these principles help our components to be unit tested with ease.\n\n* '''Powerful abstractions:''' JSX and the Virtual DOM a allow us to write declarative code and abstract us away from the DOM rendering and reconciliation details.\n\n* '''Ecosystem and community:''' The React community and there is a huge number of libraries and frameworks with a high degree of diversity.\n\n* '''Consistent user experience:''' Web components can help to create a consistent user experience across an entire application or even an organization as a whole. Web components can help our applications to adhere to style guides with ease.\n\n\n<br />\n==The React ecosystem==\n<span style=\"color:#000080\">As we have already learned, React is a library, not a framework.</span>\n\n<span style=\"color:#000080\">React is inspired by the UNIX philosophy:</span>\n:: <span style=\"color:#000080\">'''Do one thing and do it well'''.</span>\n\n<span style=\"color:#FF0000\">So React is very good at one thing: allow developers to build UI components. However, React doesn't tinclude support for some of the most common features in SPAs. For example, React doesn't include any routing or navigation-related features, data fetching features or state management features among many others.</span>\n\n<span style=\"color:#000080\">If we want to build a real-world professional SPA, it is highly likely that we will need some additionallibraries. The good news is that the React ecosystem is very extensive and we will almost certainly findan already existing library that can do what we are looking for.</span>\n\n<span style=\"color:#000080\">The React ecosystem also follows the UNIX philosophy. This means that we will have to install a numberof tools because each tool will only do one thing. For example, the '''''react-dom''''' module renders the React application using the DOM API while the '''''react-router-dom''''' module can be used to implement routing in web browsers. These modules do only one thing, but they do it very well.</span>\n\nThis architectural style has some pros and cons. We can say that React allows us to select the best tool for the job and does't decide anything for us. React gives us more options and, as a result, getting started with React can be being more time-consuming.\n\nAlso, because the Raact ecosystem is very diverse and sometimes each project comes from a different author, there is a higher risk of projects being abandoned.\n\n\n<br />\n==Install React==\nWe need to install the '''''create-react-app''''' command using npm. Because we are going to invoke the '''''create-react-app''''' command from our terminal, we need to install it as a global dependency using the -g flag:\n\n<syntaxhighlight lang=\"shell\">\nnpm install -g create-react-app\n</syntaxhighlight> \n\n\n<br />\n==Creating a React project==\nIn the past, creating a React application used to be a very tedious and complicated task. However,things have gotten much better over time and today we can auto-generate an entire React application in just a few minutes using the '''''create-react-app''''' command. \n\nWe are going to use the '''''create-react-app''''' to scaffold out a basic React app from the terminal in just a couple of minutes.\n\nTo generate a new React application with TypeScript support, we need to execute the following command:\n<syntaxhighlight lang=\"shell\">\ncreate-react-app myreactapp --typescript\n</syntaxhighlight> \n\nThe preceding command will generate a folder named ''myreactapp'' the current directory. This operation can take a few minutes, so please be patient. \n\nIt is recommended to create the application in a directory that is unlikely to be affected by permissions-related restrictions. For example, you can use the CODE directory under your user's home directory (~/CODE/home).\n\nIf everything works correctly, a new folder named ''myreactapp'' should be created in the current directory and it should contain the following files and folders:\n\n<syntaxhighlight lang=\"shell\">\n.\n|--README.md\n|--node_modules\n|   `-- ...\n|--public\n|   |--favicon.ico\n|   |--index.html\n|   `--manifest.json\n|--src\n|   |--App.css\n|   |--App.test.tsx\n|   |--App.tsx\n|   |--index.css\n|   |--index.tsx\n|   |--logo.svg\n|   |--react-app-env.d.ts\n|   `--serviceWorker.ts\n|--package-lock.json\n|--package.json\n`--tsconfig.json\n</syntaxhighlight> \n\n<span style=\"color:#000080\">It is essential to ensure that the extension of some of the files such as the index.tsx is .tsx andnot .js. When we execute the ''create-react-app'' with the ''--typescript'' flag, we are creating a ''TypeScript'' project, and the file extension will be ''.tsx''. However, if we forget the flag, the ''create-react-app'' command will generate a ''JavaScript'' project and the extension of the ''index.tsx'' file will be ''.js'' instead of ''.tsx''. If the file extension is wrong, you should delete the entire project folder and create a new project using the ''--typescript'' flag.</span>\n\n\n<br />\n\n===package json===\nThe project generated by the ''create-react-app'' command contains the following '''''package.json''''' file:\n\n<syntaxhighlight lang=\"json\">\n{\n  \"name\": \"myreactapp\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"@types/jest\": \"24.0.6\",\n    \"@types/node\": \"11.9.4\",\n    \"@types/react\": \"16.8.4\",\n    \"@types/react-dom\": \"16.8.2\",\n    \"react\": \"^16.8.2\",\n    \"react-dom\": \"^16.8.2\",\n    \"react-scripts\": \"2.1.5\",\n    \"typescript\": \"3.3.3\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"test\": \"react-scripts test\",\n    \"eject\": \"react-scripts eject\"\n  },\n  \"eslintConfig\": {\n    \"extends\": \"react-app\"\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ]\n}\n</syntaxhighlight> \n\nAs we can see in the preceding code snippet, the auto-generated ''package.json'' file contains some default npm scripts commands:\n* '''npm run start''' can be used to start running our React application using a local development server.\n\n* '''npm run build''' can be used to build our React application into an application bundle that we can deploy to a hosting provider.\n\n* '''npm run test''' can be used to execute the unit and integration tests in our React application.\n\n* '''npm run eject''' can be used to make some internal configuration public. One example is the '''''Webpack''''' configuration file. ''Webpack'' is a tool that is used to compile, minimize and bundle front-end applications into highly optimized files. We do this because it helps to reduce the loading times of our applications. However, configuring ''Webpack'' is a complex and tedious task. The ''create-react-app'' project hides this complexity from us. We are free to expose the complexity using the ''eject'' npm script.\n\n\nPlease note that it is not possible to rollback the changes performed by the eject npm script command.\n\n\n<br />\n===tsconfig json===\ntsconfig json is another important file generated by the ''create-react-app'' command. This file contains the TypeScript compiler options.\n\n\n<br />\n==Run the App==\nNow that we know about the npm scripts generated by '''''create-react-app''''' in the '''''package.json''''' file, we are going to run our application using the start command. When in the linux terminal you execute ''npm run start'', this execute ''react-scripts start'' and start the App in the Web Browser:\n\n<syntaxhighlight lang=\"shell\">\nnpm run start\n</syntaxhighlight>\n\n\nAt this point, we should be able to see our React application displayed on the screen:\n[[File:The_default_application_generated_by_the_create-react-app_command.png|900px|thumb|center|The default application generated by the ''create-react-app'' command]]\n\nAs we can see in the default application, the following message is displayed on the screen:\n Edit src/App.tsx and save to reload\n\nThe local web server started by the ''npm run start'' command automatically reloads the React application when a change in the source code is detected. This is very similar to the way ''nodemon'' behaves as we learned during the first part of this course.\n\n\n<br />\n==JSX==\nhttps://reactjs.org/docs/introducing-jsx.html\n\n<nowiki>\n const element = <h1>Hello, world!</h1>;\n</nowiki>\n\nThis funny tag syntax is neither a string nor HTML. It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript. JSX produces React \"elements\". We will explore rendering them to the DOM.\n\n\n<br />\n\n==App tsx==\nWe are now going to take a look to the source code of the ''src/App.tsx'' file that was generated by the ''create-react-app'' command:\n\n<syntaxhighlight lang=\"ts\">\nimport React, { Component } from 'react';\nimport logo from './logo.svg';\nimport './App.css';\n\nclass App extends Component {\n  render() {\n    return (\n      <div className=\"App\">\n        <header className=\"App-header\">\n          <img src={logo} className=\"App-logo\" alt=\"logo\" />\n          <p>\n            Edit <code>src/App.tsx</code> and save to reload.\n          </p>\n          <a\n            className=\"App-link\"\n            href=\"https://reactjs.org\"\n            target=\"_blank\"\n            rel=\"noopener noreferrer\"\n          >\n            Learn React\n          </a>\n        </header>\n      </div>\n    );\n  }\n}\n\nexport default App;\n</syntaxhighlight>\n\n\nLet's ignore the entire code snippet and only focus on the following section for now:\n<syntaxhighlight lang=\"ts\">\n<p>\n  Edit <code>src/App.tsx</code> and save to reload.\n</p>\n</syntaxhighlight>\n\n\nThis is the sentence that was displayed on the screen when we started the local web server. We are going to change the preceding code snippet to something like the following:\n<syntaxhighlight lang=\"ts\">\n<p>\n  Hello React!\n</p>\n</syntaxhighlight>\n\n\nThen, if we save the changes to the file, our browser will automatically be refreshed and we will see thenew sentence displayed on the screen.\n\n\n<br />\n==index css==\nIn this file we can set some global attributes. For example, let's define a different padding for the body:\n\n src/index.css\n<syntaxhighlight lang=\"ts\">\nbody {\n  margin: 0;\n  padding: 30px;\n  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',\n    sans-serif;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',\n    monospace;\n}\n</syntaxhighlight>\n\n\n<br />\n\n==index tsx and index html==\nindex.tsx is the application entry point:\n\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\nReactDOM.render(<App />, document.getElementById('root'));\n\n// If you want your app to work offline and load faster, you can change\n// unregister() to register() below. Note this comes with some pitfalls.\n// Learn more about service workers: http://bit.ly/CRA-PWA\nserviceWorker.unregister();\n</syntaxhighlight>\n\n\nIn general, React generates html. So, to render (\u00abrender\u00bb means \"to execute the code and generate the html\") the App in the client site we need:\n\n import ReactDOM from 'react-dom';\n\n''react-dom'' have a method call '''''render''''' (''ReactDom.render'') that is the method that executes the code and generates the ''html'':\n\n ReactDOM.render(<App />, document.getElementById('root'));\n\nIn the previous line, we are basically saying, we want to render the <App /> component, and we want to render it into '''''document.getElementById('root')''''' (so into the Element of the Document with ID 'root'). In other words, there is a ''html'' page, and in this page there is an element with ID root and inside this element is where the React App is going to be run. You can check this by going to the '''''public/index.html''''' file. Notice in this file:\n\n* '''<nowiki> <div id=\"root\"> <d/iv> </nowiki>''' : Inside this <nowiki> <div> </nowiki> is where '''''ReactDOM.render''''' is going to place the ''html'' generated by React.\n* '''<nowiki> <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" /> </nowiki>''' : That line is going to load the ''manifest.json'', which is going to ''render'' the ''React Applicatino'' into the above <nowiki> <div> </nowiki>.\n\n\nWe said that we are creating a single web page App because what the server send to the client is only one page, which is that '''''index.html''''' page. Then, the ''Reanc Application'' can have as many pages as we want, but they are all generated in the client site.\n\n\nLet's make some change in index.tsx:\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\n\nconst element = <h1>Helo</h1>;\n\nReactDOM.render(element, document.getElementById('root'));\n\n// If you want your app to work offline and load faster, you can change\n// unregister() to register() below. Note this comes with some pitfalls.\n// Learn more about service workers: http://bit.ly/CRA-PWA\nserviceWorker.unregister();\n</syntaxhighlight>\n\n\nWith the above changes, what is going to be rendered into ''document.getElementById('root')'' is ''element''. So the Application in your web browser is going to show only \"Hello\".\n\nThat was just an example, but what we usually do is to create components.\n\n\n<br />\n\n==Components - Example 1==\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\n\nclass MyComponent extends React.Component {\n    public render(){\n        const element = <h1>Hello</h1>;\n        return element;\n    }\n}\n\nReactDOM.render(<MyComponent/>, document.getElementById('root'));\n</syntaxhighlight>\n\nThis component becomes a ''html tag'', and that is why we can render it this way: <MyComponent/>. Now we can use our <MyComponent/> html tag as many times as we want and so reuse code.\n\nIn the above example we render our <MyComponent/> tag, but we can also use standard ''html'' tags, <nowiki> <div> </nowiki> for example. We can do something like this:\n\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\n\nclass MyComponent extends React.Component {\n    public render(){\n        const element = <h1>Hello</h1>;\n        return element;\n    }\n}\n\nReactDOM.render(\n    <div>\n        <MyComponent/>\n        <MyComponent/>\n        <MyComponent/>\n        <MyComponent/>\n    </div>,\n    document.getElementById('root')\n);\n</syntaxhighlight>\n\n\nLet's do a more realistic example. Suppose that we want to create a Header with a particular style. In a company, for example, we want to make sure that every time someone need a header, this is going to be the same. We don't want the header in one page to look one way and in a different way in another page. We can for example define the CSS style of our component this way:\n\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\n\nclass MyComponent extends React.Component {\n    public render(){\n        const style: React.CSSProperties = {\n            borderBottom: \"1px solid blue\"\n        };\n        const element = <h1 style={style}>Hello</h1>;\n        return element;\n    }\n}\n\nReactDOM.render(\n    <div>\n        <MyComponent/>\n        <MyComponent/>\n        <MyComponent/>\n        <MyComponent/>\n    </div>,\n    document.getElementById('root')\n);\n</syntaxhighlight>\n\nIt is very important to notice that:\n* The value of the variable ''style'' (that is an object) is going to be the CSS of our component.\n* '''''React.CSSProperties''''' is the type of the variable (''style'') we are creating. Remenber that in TypeScript we need to define the type of the variable.\n*  Also, notice that in CSS, the attribute we are defining would be ''border-bottom'', but in react (JSX) is ''borderBottom''.\n\n\nWe can also define argument in our components. Let's see how to do so:\n\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\n\ninterface HeaderProps {\n    title: string;\n}\n\ninterface HeaderState {\n\n}\n\n\nclass Header extends React.Component<HeaderProps, HeaderState> {\n    public render(){\n        const style: React.CSSProperties = {\n            borderBottom: \"1px solid blue\"\n        };\n        const element = <h1 style={style}>{this.props.title}</h1>;\n        return element;\n    }\n}\n\n\nReactDOM.render(\n    <div>\n        <Header title=\"Header 1\"/>\n        <Header title=\"Header 2\"/>\n        <Header title=\"Header 3\"/>\n        <Header title=\"Header 4\"/>\n    </div>,\n    document.getElementById('root')\n);\n</syntaxhighlight>\n\n\nNotice that we have also changed the name of our component from \u00abMyComponent\u00bb to \u00abHeader\u00bb (just to make it a bit more realistic).\n\n\nNow, we just should move our Header component into a separate file in a folder called \u00abcomponents\u00bb:\n\n src/components/header/header.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\n\ninterface HeaderProps {\n    title: string;\n}\n\ninterface HeaderState {\n\n}\n\n\nexport class Header extends React.Component<HeaderProps, HeaderState> {\n    public render(){\n        const style: React.CSSProperties = {\n            borderBottom: \"1px solid blue\"\n        };\n        const element = <h1 style={style}>{this.props.title}</h1>;\n        return element;\n    }\n}\n</syntaxhighlight>\n\nNotice the \u00abexport\u00bb that have to be added before the \u00abclass\u00bb.\n\n\nNow we have to export our Header component in \u00abindex.tsx\u00bb:\n\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\nimport {Header } from \"./components/header/header\"\n\n\nReactDOM.render(\n    <div>\n        <Header title=\"Header 1\"/>\n        <Header title=\"Header 2\"/>\n        <Header title=\"Header 3\"/>\n        <Header title=\"Header 4\"/>\n    </div>,\n    document.getElementById('root')\n);\n</syntaxhighlight> \n\n\n\nLet's add another properties to our component.\n\n src/components/header/header.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\n\ninterface HeaderProps {\n    size: number;\n    title: string;\n    enableBaclgroud: boolean;\n}\n\ninterface HeaderState {\n\n}\n\n\nexport class Header extends React.Component<HeaderProps, HeaderState> {\n    public render(){\n        const style: React.CSSProperties = {\n            borderBottom: \"1px solid blue\",\n            backgroundColor: this.props.enableBaclgroud ? \"red\" : \"none\"\n        };\n        switch(this.props.size){\n            case 1:\n                return <h1 style={style}>{this.props.title}</h1>;\n            case 2:\n                return <h2 style={style}>{this.props.title}</h2>;\n            case 3:\n                return <h3 style={style}>{this.props.title}</h3>;\n            case 4:\n                return <h4 style={style}>{this.props.title}</h4>;\n            default:\n                return new Error(\"Invalid size\");\n        }\n    }\n}\n</syntaxhighlight> \n\nNotice the line: \n backgroundColor: this.props.enableBaclgroud ? \"red\" : \"none\"\nThe above line is saying:\n if this.props.enableBaclgroud = true: backgroundColor is \u00abred\u00bb,\n if false: \u00abnone\u00bb\n\n\nThen,\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\nimport {Header } from \"./components/header/header\"\n\n\nReactDOM.render(\n    <div>\n        <Header size={1} title=\"Header 1\" enableBaclgroud={true}  />\n        <Header size={1} title=\"Header 2\" enableBaclgroud={false} />\n        <Header size={1} title=\"Header 3\" enableBaclgroud={true}  />\n        <Header size={1} title=\"Header 4\" enableBaclgroud={false} />\n    </div>,\n    document.getElementById('root')\n);\n</syntaxhighlight> \n\n\nNow suppose that we want to implement a more difficult code. If we want, for example, implement an \u00abif, else\u00bb inside a JSX block (inside the <nowiki> <h1> </h1> </nowiki>, for example):\n\n src/components/header/header.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\n\ninterface HeaderProps {\n    size: number;\n    title: string;\n    enableBaclgroud: boolean;\n}\n\ninterface HeaderState {\n\n}\n\n\nexport class Header extends React.Component<HeaderProps, HeaderState> {\n    public render(){\n        const style: React.CSSProperties = {\n            borderBottom: \"1px solid blue\",\n            backgroundColor: this.props.enableBaclgroud ? \"red\" : \"none\"\n        };\n        switch(this.props.size){\n            case 1:\n                return <h1 style={style}>\n                    {\n                        (() => {\n                            if (true) {\n                                return \"Hello\";\n                            } else {\n                                return \"World\";\n                            }\n                        })()\n                    }\n                    {this.props.title}\n                </h1>;\n            case 2:\n                return <h2 style={style}>{this.props.title}</h2>;\n            case 3:\n                return <h3 style={style}>{this.props.title}</h3>;\n            case 4:\n                return <h4 style={style}>{this.props.title}</h4>;\n            default:\n                return new Error(\"Invalid size\");\n        }\n    }\n}\n</syntaxhighlight> \n\n\nAnother and better aproach is to create another method: \n\n src/components/header/header.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\n\ninterface HeaderProps {\n    size: number;\n    title: string;\n    enableBaclgroud: boolean;\n}\n\ninterface HeaderState {\n\n}\n\n\nexport class Header extends React.Component<HeaderProps, HeaderState> {\n    public render(){\n        const style: React.CSSProperties = {\n            borderBottom: \"1px solid blue\",\n            backgroundColor: this.props.enableBaclgroud ? \"red\" : \"none\"\n        };\n        switch(this.props.size){\n            case 1:\n                return <h1 style={style}>\n                    {this._renderConditional()}\n                    {this.props.title}\n                </h1>;\n            case 2:\n                return <h2 style={style}>{this.props.title}</h2>;\n            case 3:\n                return <h3 style={style}>{this.props.title}</h3>;\n            case 4:\n                return <h4 style={style}>{this.props.title}</h4>;\n            default:\n                return new Error(\"Invalid size\");\n        }\n    }\n\n\n    private _renderConditional(){\n        if (true) {\n            return \"Hello\";\n        } else {\n            return \"World\";\n        }\n    }\n\n}\n</syntaxhighlight> \n\nThe _ in _renderConditional() is just a convention that is usually used in many languages to make clear that we are talking about a private element.\n\n\nLet's create another component:\n\n src/components/panel/panel.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\n\ninterface PanelProps {\n    header: string;\n    body:   string;\n    footer: string;\n}\n\ninterface PanelState {\n\n}\n\n\nexport class Panel extends React.Component<PanelProps, PanelState> {\n    public render(){\n        const panelStyle: React.CSSProperties = {\n            border: \"1px solid #333333\",\n            background: \"blue\",\n            borderRadius: \"5px\"\n        };\n        const headerStyle: React.CSSProperties = {\n            padding: \"5px\",\n            borderBottom: \"1px solid #333333\",\n        };\n        const bodyStyle: React.CSSProperties = {\n            padding: \"5px\",\n            borderBottom: \"1px solid #333333\",\n        };\n        const footerStyle: React.CSSProperties = {\n            padding: \"5px\",\n            borderBottom: \"1px solid #333333\",\n        };\n        return <div style={panelStyle}>\n            <div style={headerStyle}>{this.props.header}</div>\n            <div style={bodyStyle}>{this.props.body}</div>\n            <div style={footerStyle}>{this.props.footer}</div>\n        </div>;\n    }\n\n}\n</syntaxhighlight>\n\n\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\nimport {Header } from \"./components/header/header\"\nimport {Panel } from \"./components/panel/panel\"\n\n\nReactDOM.render(\n    <div>\n        <Header size={1} title=\"Header 1\" enableBaclgroud={true}  />\n        <Header size={1} title=\"Header 2\" enableBaclgroud={false} />\n        <Header size={1} title=\"Header 3\" enableBaclgroud={true}  />\n        <Header size={1} title=\"Header 4\" enableBaclgroud={false} />\n        <Panel  header={\"The header\"} body={\"The body\"} footer={\"The footer\"} />\n    </div>,\n    document.getElementById('root')\n);\n</syntaxhighlight>\n\n\n<br />\n\n==Components - Example 2==\n\n src/components/header/header.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\n\ninterface HeaderProps {\n    label: string;\n    color?: string;\n}\n\ninterface HeaderState {\n\n}\n\n\nexport class Header extends React.Component<HeaderProps, HeaderState> {\n    public render(){\n        const style: React.CSSProperties = {\n            fontFamily: `Rubik,Lato,\"Lucida Grande\",\"Lucida Sans Unicode\",Tahoma,Sans-Serif`,\n            fontSize: \"56px\",\n            fontWeight: 700,\n            color: this.props.color !== undefined ? this.props.color : \"#000000\",\n            borderBottom: \"3px solid\"\n        };\n        return <div>\n            <h1 style={style}>{this.props.label}</h1>\n        </div>\n    }\n\n    \n}\n</syntaxhighlight>\n\nIn the example above, we have defined an optional property for the Header component. Notice that \u00abcolor?\u00bb has been defined with a \u00ab?\u00bb at the end. This means that we can user (or not) the color property when using the Header component. Also notice that, when we declare an optional property, this need to be defined using an \u00abelse, if\u00bb block. So this way we define what happens when the property is used and when is not used. This was made in the above code this way:\n\n color: this.props.color !== undefined ? this.props.color : \"#000000\",\n\nThis line means: in case the property is defined, this.props.color : \"#000000\",\n\n\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\nimport {Header } from \"./components/header/header\";\nimport {Panel } from \"./components/panel/panel\";\n\n\nReactDOM.render(\n    <div>\n        <Header label=\"My Header 1\" />\n        <Panel\n            header=\"The header\"\n            body=\"The body\"\n            footer=\"The footer\"\n        />\n\n    </div>,\n    document.getElementById('root')\n);\n</syntaxhighlight>\n\n\nLet's now create another component:\n \n src/components/listview/listview.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\n\ninterface ListviewProps {\n    items: string[];\n}\n\ninterface ListviewState {\n\n}\n\n\nexport class Listview extends React.Component<ListviewProps, ListviewState> {\n    public render(){\n        if (this.props.items.length < 1){\n            return <div>There if no items</div>;\n        } else {\n            return <div>{this.props.items}</div>;\n        }\n    }\n\n}\n</syntaxhighlight>\n\n\n<br />\n===Mapping data into JSX elements===\n<span style=\"color:#FF0000\">'''This is how in react we transform data into JSX elements.'''</span>\n\n\nSuppose that we have an array of number (data):\n var arr = [1, 2, 3, 4, 5];\n\nWe can use the \u00abmap\u00bb function of the \u00abarr\u00bb class to make change in our array:\n var arr2 = arr.map(function (n) {return n * 2});\nIn this caes \u00abarr2\u00bb is going to contain [2, 4, 6, 8, 10]\n\n\nWe can also transform an array of number into an array of strings: [\"1\", \"2\", \"3\", \"4\", \"5\"]\n var arr3 = arr.map(function (n) {return n.toString()});\n\n\nBut another more interested thing that we can do, is to transform the array of number into an array of react elements (JSX elements). For example:\n<syntaxhighlight lang=\"ts\">\nvar arr4 = arr.map(function (n) {return <li>{n}</li>});\n</syntaxhighlight>\n\n\nThe last code ins going to return:\n<syntaxhighlight lang=\"css\">\n[<li>1</li>, <li>2</li>, <li>3</li>, <li>4</li>, <li>5</li>]\n</syntaxhighlight>\n\n\nSo, we are going to use the \u00abmap\u00bb function into our Listview component to generate a list:\n src/components/listview/listview.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\n\ninterface ListviewProps {\n    items: string[];\n}\n\ninterface ListviewState {\n\n}\n\n\nexport class Listview extends React.Component<ListviewProps, ListviewState> {\n    public render(){\n        if (this.props.items.length < 1){\n            return <div>There if no items</div>;\n        } else {\n            return <ul>\n                {this.props.items.map(function (item) {\n                    return <li>{item}</li>\n                })}\n            </ul> ;\n        }\n    }\n\n}\n</syntaxhighlight>\n\n\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\nimport {Header } from \"./components/header/header2\";\nimport {Panel } from \"./components/panel/panel\";\nimport {Listview } from \"./components/listview/listview\";\n\n\nReactDOM.render(\n    <div>\n        <Header label=\"My Header 1\" />\n        <Panel\n            header=\"The header\"\n            body=\"The body\"\n            footer=\"The footer\"\n        />\n        <Listview items={[\"Titanic\", \"Interview with the vampire\", \"The Lion King\"]} />\n    </div>,\n    document.getElementById('root')\n);\n</syntaxhighlight>\n\n\n<br />\n\n===A component inside another component===\nLet's create a card component:\n\n src/components/card/card.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\n\ninterface CardProps {\n    child: JSX.Element;\n}\n\ninterface CardState {\n\n}\n\n\nexport class Card extends React.Component<CardProps, CardState> {\n    public render(){\n        const style: React.CSSProperties = {\n            border: \"1px solid #eeeeee\",\n            boxShadow: \"0 10px 6px -6px #777\"\n        };\n        return <div style={style}>\n            {this.props.child}\n        </div>\n    }\n\n\n}\n</syntaxhighlight>\n\nNotice that we have passed a property of type '''JSX.Element'''. Now, we can pass another component to our Card component: \n\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\nimport {Header } from \"./components/header/header2\";\nimport {Panel } from \"./components/panel/panel\";\nimport {Listview } from \"./components/listview/listview\";\nimport {Card } from \"./components/card/card\";\n\n\nReactDOM.render(\n    <div>\n        <Header label=\"My Header 1\" />\n        <Panel\n            header=\"The header\"\n            body=\"The body\"\n            footer=\"The footer\"\n        />\n        <Listview items={[\"Titanic\", \"Interview with the vampire\", \"The Lion King\"]} />\n        <Card child={<Listview items={[\"Titanic\", \"Interview with the vampire\", \"The Lion King\"]} />}/>\n    </div>,\n    document.getElementById('root')\n);\n</syntaxhighlight>\n\n\n<span style=\"background:#D8BFD8\">'''However, there is a standard and better way to do so:'''</span>\n\nWe know that there are tow ways of open and close an element. We can do is this way:\n <Header/>\n <Header label=\"My Header 1\" />\n\nOr we can do it this way:\n <Card>\n </Card>\n\nIn the last case we can put something in the medle, for example:\n<syntaxhighlight lang=\"html\">\n<Card>\n    <Listview items={[\"Titanic\", \"Interview with the vampire\", \"The Lion King\"]} />\n</Card>\n</syntaxhighlight>\n\nwhich is the standard way to pass an element inside another element. In this case we don't need to define a \u00abclild\u00bb property in the \u00abProps\u00bb interface; and we can use the \u00abchildren\u00bb special property (that don't need to be defined in the \u00abProps\u00bb interface because is defined by default) to refer to this child element. Let's see that in code:\n\n src/components/card/card.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\n\ninterface CardProps {\n\n}\n\ninterface CardState {\n\n}\n\n\nexport class Card extends React.Component<CardProps, CardState> {\n    public render(){\n        const style: React.CSSProperties = {\n            border: \"1px solid #eeeeee\",\n            boxShadow: \"0 10px 6px -6px #777\",\n            marginBottom: \"30px\"\n        };\n        return <div style={style}>\n            {this.props.children}\n        </div>\n    }\n\n\n}\n</syntaxhighlight>\n\n\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\nimport {Header } from \"./components/header/header2\";\nimport {Panel } from \"./components/panel/panel\";\nimport {Listview } from \"./components/listview/listview\";\nimport {Card } from \"./components/card/card\";\n\n\nReactDOM.render(\n    <div>\n        <Header label=\"My Header 1\" />\n        <Panel\n            header=\"The header\"\n            body=\"The body\"\n            footer=\"The footer\"\n        />\n        <Listview items={[\"Titanic\", \"Interview with the vampire\", \"The Lion King\"]} />\n        <Card>\n            <Listview items={[\"Titanic\", \"Interview with the vampire\", \"The Lion King\"]} />\n        </Card>\n    </div>,\n    document.getElementById('root')\n);\n</syntaxhighlight>\n\n\n<br />\n===States===\nIf we want, for example, an element to be collapsed or expanded, we have to use the \u00abState Interface\u00bb of the component:\n\n<syntaxhighlight lang=\"ts\">\n...\n\ninterface CardState {\n    isCollapsed: boolean;\n}\n...\n</syntaxhighlight>\n\n\nLet's see an example:\n src/components/card/card.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\n\ninterface CardProps {\n\n}\n\ninterface CardState {\n    isCollapsed: boolean;\n}\n\n\nexport class Card extends React.Component<CardProps, CardState> {\n    public constructor(props: CardProps){\n        super(props);\n        this.state = {\n            isCollapsed: false\n        }\n    }\n\n    public render(){\n        const style: React.CSSProperties = {\n            border: \"1px solid #eeeeee\",\n            boxShadow: \"0 10px 6px -6px #777\",\n            marginBottom: \"30px\"\n        };\n        return <div style={style}>\n            <button onClick={() => this._toggle()}>\n                {this.state.isCollapsed ? \"Open\" : \"Close\"}\n            </button>\n            {/* Now we need to do an \u00abif - else\u00bb to show or not the \n                 childre depending on the value of \u00abisCollapsed\u00bb \n                 We can do an \u00abif - else\u00bb inside the JSX block in \n                 different ways: */ }\n            {/* 1. Using a function that calls itself: */}\n            {\n                (() => {\n                    if (this.state.isCollapsed){\n                        return null;\n                    } else {\n                        return this.props.children;\n                    }\n                })()\n            }\n            {/* 2. Defining the block in one line this way: */}\n            {/* {this.state.isCollapsed ? null : this.props.children} */}\n            {/* 3. Creating another method: */}\n            {/* {this._renderChildren()} */}\n        </div>\n    }\n\n    private _renderChildren(){\n        if (this.state.isCollapsed) {\n            return null;\n        } else {\n            return this.props.children;\n        }\n    }\n\n    private _toggle(){\n        // this.state.isCollapsed = false; // This way is not going to work. this has to be done useing \u00absetState\u00bb, because \u00absetState\u00bb rerender the html\n        this.setState({isCollapsed: !this.state.isCollapsed });\n    }\n\n\n}\n</syntaxhighlight>\n\n\n'''From the last code, notice:'''\n\n* When we use states, we also need to define the initial state. To do so, we need to add a \u00abconstructor\u00bb to our class:\n<blockquote>\n<syntaxhighlight lang=\"ts\">\npublic constructor(props: CardProps){\n    // We first need to call the constructor of the superclass and pass it as a parameter a variable of type \u00abCardProps\u00bb:\n    super(props); \n    // Then we have to define the initial state of the attributes in the \u00abstate interface\u00bb:\n    this.state = {\n        isCollapsed: false\n    }\n}\n</syntaxhighlight>\n</blockquote>\n\n\n* Then, we need to create a method that is going to chage the value of the \u00abstate attribute\u00bb (in our example \u00abisCollapsed\u00bb) and is going to rerender the html when the state changes:\n<blockquote>\n<syntaxhighlight lang=\"ts\">\nprivate _toggle(){\n    // We are setting \u00abisCollapsed\u00bb equal to the opposite (!) of its value\n    // The \u00absetState\u00bb method is in charge of render the application. If the application is not rendered, we will never see the changes in the page.\n    this.setState({isCollapsed: !this.state.isCollapsed });\n}\n</syntaxhighlight>\n</blockquote>\n\n\n* Then, we define a button that execute the \u00ab_toggle\u00bb method on click:\n<blockquote>\n<syntaxhighlight lang=\"ts\">\n<button onClick={() => this._toggle()}>\n    {this.state.isCollapsed ? \"Open\" : \"Close\"}\n</button>\n</syntaxhighlight>\nEvery time we click in this button, the value of \u00abisCollapsed\u00bb is changed to its opposite and the application is rendered.\n</blockquote>\n\n\n* Finally, we define what is going to happen depending on the value of \u00abisCollapsed\u00bb. In our example, we need to do an \u00abif - else\u00bb block so:\n<blockquote>\n<syntaxhighlight lang=\"ts\">\nif (this.state.isCollapsed == true){\n    return null;                // Nothing in the page\n} else {\n    return this.props.children; // The child component\n}\n</syntaxhighlight>\nOnly when the value of \u00abisCollapsed\u00bb is false, we are going to show the child component in the page.\n\n\n'''There are different ways to do an \u00abif - else\u00bb inside a JSX block:'''\n<blockquote>\n\n: 1. Using a function that calls itself:\n<blockquote>\n<syntaxhighlight lang=\"ts\">\n(() => {\n    if (this.state.isCollapsed){\n        return null;\n    } else {\n        return this.props.children;\n    }\n})()\n</syntaxhighlight>\n</blockquote>\n\n\n: 2. Defining the block in one line this way:\n<blockquote>\n<syntaxhighlight lang=\"ts\">\n{this.state.isCollapsed ? null : this.props.children}\n</syntaxhighlight>\n</blockquote>\n\n\n: 3. Creating another method:\n<blockquote>\n<syntaxhighlight lang=\"ts\">\n// Inside the JSX block:\n{this._renderChildren()}\n\n// Outside the JSX block:\nprivate _renderChildren(){\n    if (this.state.isCollapsed) {\n        return null;\n    } else {\n        return this.props.children;\n    }\n}\n</syntaxhighlight>\n</blockquote>\n\n\n<br />\n\n==Components - Fetching data from the server==\n\n\n<br />\n===Example 1===\nWe are going to create a '''\u00ab.json\u00bb''' file that is going to simulate data that come from the server. So, we are going to create a folder inside the \u00abpublic\u00bb folder called \u00abdata\u00bb and inside this folder our \u00ab.json\u00bb file. We are creating thsi \u00ab.json\u00bb file because this is the format in which data from the server will come.\n\n public/data/cats.json\n<syntaxhighlight lang=\"json\">\n[\n    \"https://images.pexels.com/photos/257540/pexels-photo-257540.jpeg\",\n    \"https://images.unsplash.com/photo-1518791841217-8f162f1e1131\",\n    \"https://news.nationalgeographic.com/content/dam/news/2018/05/17/you-can-train-your-cat/02-cat-training-NationalGeographic_1484324.ngsversion.1526587209178.adapt.1900.1.jpg\",\n    \"https://images.unsplash.com/photo-1532386236358-a33d8a9434e3\",\n    \"https://ichef.bbci.co.uk/images/ic/720x405/p0517py6.jpg\",\n    \"https://cdn.cnn.com/cnnnext/dam/assets/150324154010-04-internet-cats-restricted-super-169.jpg\"\n]\n</syntaxhighlight>\n\n\nNow, let's create a \u00absrc/pages\u00bb folder and inside it our first page. We will start by a hard code example. In this example, nothing comes from the server nor from public/data/cats.json, but this way we can understand some aspects:\n\n src/pages/cats.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\nimport {Carousel } from \"../components/carousel/carousel\";\n\ninterface CatsProps {\n\n}\n\ninterface CatsState {\n\n}\n\n\nexport class Cats extends React.Component<CatsProps, CatsState> {\n    public render(){\n        const imgStyle: React.CSSProperties = { width: \"100px\", height: \"100px\"};\n        return (\n            <Carousel\n                items={[\n                    <img style={imgStyle} src=\"https://images.pexels.com/photos/257540/pexels-photo-257540.jpeg\" />,\n                    <img style={imgStyle} src=\"https://images.unsplash.com/photo-1518791841217-8f162f1e1131\" />,\n                    <img style={imgStyle} src=\"https://ichef.bbci.co.uk/images/ic/720x405/p0517py6.jpg\" />\n                ]}\n                startInIndex={0}\n            />\n        );\n    }\n\n}\n</syntaxhighlight>\n\nIt is important to notice that, in React, '''a page is also a component'''. We make the different only because pages are not going to be reusable. We are not going to use a page inside a component or inside another pages. But technically, React doesn't see any different between components and pages.\n\n\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\nimport {Header } from \"./components/header/header2\";\nimport {Panel } from \"./components/panel/panel\";\nimport {Listview } from \"./components/listview/listview\";\nimport {Card } from \"./components/card/card\";\nimport {Cats} from \"./pages/cats\";\n\n\nReactDOM.render(\n    <div>\n        <Header label=\"My Header 1\" />\n        <Panel\n            header=\"The header\"\n            body=\"The body\"\n            footer=\"The footer\"\n        />\n        <Listview items={[\"Titanic\", \"Interview with the vampire\", \"The Lion King\"]} />\n        <Card>\n            <Listview items={[\"Titanic\", \"Interview with the vampire\", \"The Lion King\"]} />\n        </Card>\n        <Cats/>\n    </div>,\n    document.getElementById('root')\n);\n</syntaxhighlight>\n\n\nNow, we are going to replace the hard code in pages/cats.tsx that includes the images for a fetch code that will take the images from the public/data/cats.json file (which is simulating the data that comes from the server):\n\nFirst we need to create a function that is going to fetch the data from the file:\n<syntaxhighlight lang=\"ts\">\nasync function getData(){\n    const response = await fetch(\"/data/cats.json\");\n    const json = await response.json();\n    return json;\n}\n</syntaxhighlight>\n\nNotice that '''await''' has to be used because we are fetching data from the server, and we don't know how long the server is going to take to response. Also, if we use '''await''' we have to use an ''''async''' function.\n\n\nWe also need to add a \u00abstate\u00bb that is going to represent the data:\n<syntaxhighlight lang=\"ts\">\ninterface CatsState {\n    // items is type string[] or null:\n    items: string[] | null;\n}\n</syntaxhighlight>\n\n\nAlso, as we already know, when we use states, we need to use a constructor to set the initial value of the state:\n<syntaxhighlight lang=\"ts\">\npublic constructor(props: CatsProps){\n    super(props);\n    this.state = {\n        items: null\n    };\n}\n</syntaxhighlight>\n\n\nNow we need at some point call the '''getData()''' method to load the data into the page. To do so, we are going to use a special Lifecycle method called '''componentDidMount()'''. They are called like this because they are executed at a specific point of the Lifecycle of a component. The '''componentDidMount()''' it's going to be called after the component has rendered. To know more about the Lifecycle take a look at this page: https://reactjs.org/docs/state-and-lifecycle.html\n\nSo, we need to call the '''getData()''' function inside the '''componentDidMount()''' function; but we need to place '''getData()''' into a function that calls itself. We also have to call '''setState()''' to render the application when '''items''' changes:\n<syntaxhighlight lang=\"ts\">\npublic componentDidMount(){\n    (async () => {\n        const data = await getData();\n        this.setState({items: data});\n    })();\n}\n</syntaxhighlight>\nNotice that we could have called the '''getData''' and '''setState''' directly in the constructor, but this is not the correct way to do it because we don't know how long will take to have the data loaded, so the application could be rendered before the data have been loaded.\n\n\nNow, in the variable '''data''' we have an array of url, but what I need is an array of img: \n <img style={imgStyle} src=\"https://images.unsplash.com/photo-151879841217-8f162f1e1131\" />\n .\n .\n .\n\nSo we need to map our data into JSX elements (go from an array of url to an array of imgs) using the '''map''' function as we learned before:\n<syntaxhighlight lang=\"ts\">\nthis.state.items.map((item, indexItem) => {\n    return (\n        <img style={imgStyle} src={item} />\n    );\n})\n</syntaxhighlight>\n\n\nLet's talk a little about the Lifecycle to understand what is happening in our application:\n# The component is created. So the constructor is called: in our example we set the initial value of the items state as null.\n# Then, the component is going to be rendered. So the first time is rendered, items will be null and the message \u00abLoding...\u00bb will be displayed on the page.\n# After the component is rendered, '''componentDidMount()''' is called:\n:* We fetch the data using the '''getData()''' function.\n:* We call '''setState()''' and set items = data, then the component is going to be rendered again and the data will be shown in the page.\n\n\n src/pages/cats.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\nimport {Carousel } from \"../components/carousel/carousel\";\n\ninterface CatsProps {\n\n}\n\ninterface CatsState {\n    items: string[] | null;\n}\n\n\nexport class Cats extends React.Component<CatsProps, CatsState> {\n    public constructor(props: CatsProps){\n        super(props);\n        this.state = {\n            items: null\n        };\n    }\n    public componentDidMount(){\n        (async () => {\n            const data = await getData();\n            this.setState({items: data});\n        })();\n    }\n    public render(){\n        const imgStyle: React.CSSProperties = { width: \"100px\", height: \"100px\"};\n        if (this.state.items === null){\n            return <div>Loding...</div>\n        } else {\n            return (\n                <Carousel\n                    items={\n                        this.state.items.map((item, indexItem) => {\n                            return (\n                                <img style={imgStyle} src={item} />\n                            );\n                        })\n                    }\n                    startInIndex={0}\n                />\n            );\n        }\n    }\n}\n\nasync function getData(){\n    const response = await fetch(\"/data/cats.json\");\n    const json = await response.json();\n    return json;\n}\n</syntaxhighlight>\n\n\n<br />\n===Example 2===\nTo keep practicing about it, we can use this web side: http://jsonplaceholder.typicode.com/todos:\n* Create a page (todos.tsx) under the page directory\n* Use the '''componentDidMount''' event to fetch data from http://jsonplaceholder.typicode.com/todos\n* Render the list of TODOs using the <Listvies> component. \n\n\n src/pages/todos.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\nimport {Listview } from \"../components/listview/listview\";\n\n\ninterface Todo {\n    userId: number;\n    id: number;\n    title: string;\n    completed: boolean;\n}\n\ninterface TodosProps {\n\n}\n\ninterface TodosState {\n    todos: Todo[] | null;\n}\n\n\nexport class Todos extends React.Component<TodosProps, TodosState> {\n    public constructor(props: TodosProps){\n        super(props);\n        this.state = {\n            todos: null\n        };\n    }\n    public componentDidMount(){\n        (async () => {\n            const data = await getData();\n            this.setState({ todos: data });\n        })();\n    }\n    public render(){\n        const imgStyle: React.CSSProperties = { width: \"100px\", height: \"100px\"};\n        if (this.state.todos === null){\n            return <div>Loding...</div>\n        } else {\n            return (<Listview\n                    items={\n                        this.state.todos.map((todo) => {\n                            return todo.userId.toString() + \"  \" + todo.title;\n                        })\n                    }\n                />\n            );\n        }\n    }\n}\n\nasync function getData(){\n    const response = await fetch(\"http://jsonplaceholder.typicode.com/todos\");\n    const json = await response.json();\n    return json as Todo[];\n}\n</syntaxhighlight>\n\nIn the previous code, note that the property \u00abitems\u00bb of <Listview> have to be a string because in listview.tsx we defined the type of \u00abitems\u00bb as a string:\n src/components/listview/listview.tsx\n<syntaxhighlight lang=\"ts\">\n.\n.\n.\ninterface ListviewProps {\n    items: string[];\n}\n.\n.\n.\n</syntaxhighlight>\n\n\nthat is why here we have to return a string:\n src/pages/todos.tsx\n<syntaxhighlight lang=\"ts\">\n.\n.\n.\nitems={\n    this.state.todos.map((todo) => {\n        return todo.userId.toString() + \"  \" + todo.title;\n    })\n}\n.\n.\n.\n</syntaxhighlight>\n\nbut let's make a change in listview.tsx. We are going to set the type of \u00abitems\u00bb as JSX.Element[]. This way listview.tsx would looks like this:\n src/components/listview/listview2.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\n\ninterface Listview2Props {\n    items: JSX.Element[];\n}\n\ninterface Listview2State {\n\n}\n\n\nexport class Listview2 extends React.Component<Listview2Props, Listview2State> {\n    public render(){\n        if (this.props.items.length < 1){\n            return <div>There if no items</div>;\n        } else {\n            return <ul>\n                {this.props.items.map(function (item) {\n                    return <li>{item}</li>\n                })}\n            </ul> ;\n        }\n    }\n\n}\n</syntaxhighlight>\n\nNow, we are allowed to return any kind of JSX element. We can for example do something like this:\n src/pages/todos.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\nimport {Listview } from \"../components/listview/listview\";\nimport {Listview2 } from \"../components/listview/listview2\";\n\n\ninterface Todo {\n    userId: number;\n    id: number;\n    title: string;\n    completed: boolean;\n}\n\ninterface TodosProps {\n\n}\n\ninterface TodosState {\n    todos: Todo[] | null;\n}\n\n\nexport class Todos extends React.Component<TodosProps, TodosState> {\n    public constructor(props: TodosProps){\n        super(props);\n        this.state = {\n            todos: null\n        };\n    }\n    public componentDidMount(){\n        (async () => {\n            const data = await getData();\n            this.setState({ todos: data });\n        })();\n    }\n    public render(){\n        const imgStyle: React.CSSProperties = { width: \"100px\", height: \"100px\"};\n        if (this.state.todos === null){\n            return <div>Loding...</div>\n        } else {\n            return (<Listview2\n                        items={\n                            this.state.todos.map((todo) => {\n                                // To be able to return a JSX element, the type of\n                                // items have to be JSX.Element[], as was defined in <Listview2>\n                                // If we use <Listview> we have to return a string.\n                                return <div>\n                                    <input type=\"checkbox\" checked={todo.completed} />\n                                    {todo.title}\n                                </div>;\n                            })\n                        }\n                />\n            );\n        }\n    }\n}\n\nasync function getData(){\n    const response = await fetch(\"http://jsonplaceholder.typicode.com/todos\");\n    const json = await response.json();\n    return json as Todo[];\n}\n</syntaxhighlight>\n\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport App from './App';\nimport * as serviceWorker from './serviceWorker';\n\nimport {Header } from \"./components/header/header2\";\nimport {Panel } from \"./components/panel/panel\";\nimport {Listview } from \"./components/listview/listview\";\nimport {Card } from \"./components/card/card\";\nimport {Cats} from \"./pages/cats\";\nimport {Todos} from \"./pages/todos\";\n\n\nReactDOM.render(\n    <div>\n        <Header label=\"My Header 1\" />\n        <Panel\n            header=\"The header\"\n            body=\"The body\"\n            footer=\"The footer\"\n        />\n        <Listview items={[\"Titanic\", \"Interview with the vampire\", \"The Lion King\"]} />\n        <Card>\n            <Listview items={[\"Titanic\", \"Interview with the vampire\", \"The Lion King\"]} />\n        </Card>\n        <Cats/>\n        <Todos/>\n    </div>,\n    document.getElementById('root')\n);\n</syntaxhighlight>\n\n\n<br />\n\n==Routing in React==\n'''Routing is the mechanism by which requests (as specified by a URL and HTTP method) are routed to the code that handles them.'''\n\nIn a traditional web application, Routing used to be file based and very simple: if you put the file foo/about.html on your website, you would access it from the browser with the path yourdomain/foo/about.html.\n\nIn modern web application, URL Routing allows you to configure an application to accept request URLs that do not map to physical files.\n\nIn this sense, Routing enables you to use a specific path for your website. For example if you had a products website, the URL structure might be like this:\nwww.example.com/products/electronics/monitiors\n\nThis URL does not need to be linked to a specific file or directory, as products/electronics might not even exist.\n\nA URL like the one above is much easier to understand than a URL like www.example.com/products.aspx?id=250. \n\n\n\nBy default, React doesn't include a Routing module. Actually, the base React Library is very small (a diferencia de Angular where everything is built-in). Therefore, we need to add an additional library to Routing. There are many different Routing libraries that can be implemented in React. Take a look at some of the most important: https://reactjs.org/community/routing.html\n\n\n<br />\n===react-router===\nThe Routing library that we are going to implement is '''react-router''' https://github.com/ReactTraining/react-router\n\nMore specifically, we are going to use the '''react-router-dom''' package: DOM bindings for React Router. We need this one because we are going to do Routing in the browser: https://github.com/ReactTraining/react-router/tree/master/packages/react-router-dom\n\n\n<br />\n====react-router-dom installation====\n\n npm install react-router-dom         (instalaci\u00f3n global)\n npm install --save react-router-dom  (instalaci\u00f3n local, s\u00f3lo en el directorio en donde estamos trabajando. No deber\u00eda ser necesario si lo instalamos global)\n\nand because we are working with TypeScript, we also need:\n npm install @types/react-router-dom\n\n\n<br />\n====Documentation and tutorials====\nhttps://reacttraining.com/react-router/web/guides/quick-start\n\nhttps://blog.pshrmn.com/simple-react-router-v4-tutorial/\n\n\n<br />\n===Configuring the Routing in our App===\nThe routing is a global configuration of our application. We are going to configure it in index.jsx. In previous sections, we have been rendering our components and pages including then in index.jsx, but that is not the way a real Web Application would work.\n\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport * as serviceWorker from './serviceWorker';\n\nimport {BrowserRouter, Switch, Route} from 'react-router-dom';\n\nimport {Todos} from './pages/todos';\nimport {Cats} from './pages/cats';\n\n\nReactDOM.render(\n    <BrowserRouter>\n        <Switch>\n            <Route exact path=\"/\" component={Todos} />\n            <Route exact path=\"/cats\" component={Cats} />\n        </Switch>\n    </BrowserRouter>,\n    document.getElementById('root')\n);\n</syntaxhighlight>\n\nNotice:\n* import {BrowserRouter} from 'react-router-dom';\n* Now, our root component is '''<BrowserRouter>'''\n* <span style=\"color:#FF0000\">It is very important to notice that, when we change the page, the application is not going to the server to fetch a new page, this is happening in the client site, and that is why is called a Single Page Web Application.</span>\n\n\nWe can also do something like this:\n src/index.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport './index.css';\nimport * as serviceWorker from './serviceWorker';\n\nimport {BrowserRouter, Switch, Route, Link} from 'react-router-dom';\n\nimport {Todos} from './pages/todos';\nimport {Cats} from './pages/cats';\n\n\nconst headerStyle: React.CSSProperties = {\n    backgroundColor: \"#333333\",\n    height: \"100px\"\n};\n\nReactDOM.render(\n    <BrowserRouter>\n        <div>\n            <div style={headerStyle}>\n                <Link style={{ color: \"#ffffff\"}} to=\"/\">Todos</Link>\n                <Link style={{ color: \"#ffffff\"}} to=\"/cats\">Cats</Link>\n            </div>\n            <Switch>\n                <Route exact path=\"/\" component={Todos} />\n                <Route exact path=\"/cats\" component={Cats} />\n            </Switch>\n        </div>\n    </BrowserRouter>,\n    document.getElementById('root')\n);\n</syntaxhighlight>\n\n* Notice that, when we click in a link (in \u00abCats\u00bb, for example) and the URL changes, the <Cats> component is rendered, but not the whole page (not the top header that we have included). The only part that is rendered is what is inside the <Switch> component.\n\n\n<br />\n==Login Form==\nThe next page will be in charge of manage the login process:\n\n src/pages/login.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport { stringify } from 'querystring';\n\n\ninterface LoginProps {\n\n}\n\ninterface LoginState {\n    email: string;\n    password: string\n}\n\n\nexport class Login extends React.Component<LoginProps, LoginState> {\n    public constructor(props: LoginProps){\n        super(props)\n        this.state = {\n            email: \"\",\n            password: \"\"\n        };\n    }\n    public render(){\n        return(\n            <div>\n                <input\n                    type=\"text\"\n                    placeholder=\"Email\"\n                    onKeyUp={(e) => this._updateEmail((e as any).target.value)}\n                />\n                <input\n                    type=\"password\"\n                    placeholder=\"Password\"\n                    onKeyUp={(e) => this._updatePassword((e as any).target.value)}\n                />\n                <button onClick={() => this._handlerSubmit()}>Submit</button>\n            </div>\n        );\n    }\n    private _updateEmail(email: string){\n        // console.log(email);  // We can do this just to verify that the keys that are being typing into the form field are printed in the browser console.\n        this.setState({email: email});\n    }\n    private _updatePassword(password: string){\n        this.setState({password: password});\n    }\n    private _handlerSubmit() {\n        (async () => {\n            await getToken(this.state.email, this.state.password);\n        })();\n    }\n}\n\n\nasync function getToken(email: string, password: string){\n    const data = {\n        email: email,\n        password: password\n    }\n    const response = await fetch(\n        \"/api/v1/auth/login\",\n        {\n            method: \"POST\",\n            headers: {\n                'Content-type': 'application/json'\n            },\n            body: JSON.stringify(data)\n        }\n    );\n    const json = await response.json();\n    // { token: \"lasflsfooiwerojsdfosjfoijljosdifjosdfijsdfoijoweoierj\" }\n    return json.token;\n}\n</syntaxhighlight>\n\nLet's explain the above code:\n\n* We have defined two states: email and password\n\n\n* As we have already see, we need a constructor to define the initial values of the states.\n\n\n* Then, we define, inside the render method, the form that is going to be used to entered the data: The Email and Password fields and the Submit button.\n\n\n* To be able to take the Email and Password entered for the user in the form fields, We first need to be able to detect changes in the Email and Password form fields. To do so, we need to add to the <input> component, the \u00abonKeyUp\u00bb parameter, so everytime we type a key, it triggers an event and we can use this event to call any particular method that we want to execute when the user types into the form fields. In this case, we want to call the '''''_updateEmail()''''' and '''''_updatePassword()''''' methods, which are in charge of update the '''''email''''' and '''''password''''' states, respectively.\n\n\n* It is important to notice that all this kind of events:\n\n<blockquote>\n<syntaxhighlight lang=\"ts\">\nonClick={() => this._handlerSubmit()}\nonKeyUp={() => this._updateEmail()}\nonKeyPress\n.\n.\n.\netc\n</syntaxhighlight>\n</blockquote>\n\n: they always take a function ( '''onClick={ () => this._handlerSubmit() }''' ) which is calling something, and this function always take an argument that is called the event (e). For example, we can write the '''''onClick''''' function this way: '''''onClick={ (e) => this._handlerSubmit() }'''''. In the case of the '''''onClick''''', we can omit the event because we don't care which is the click event, whichever click is going to have the same effect; but in the case of '''onKeyUp''' we want to know which key has been pressed. Therefore, we have to write the '''''onKeyUp''''' this way:\n\n<blockquote>\n<syntaxhighlight lang=\"ts\">\nonKeyUp={(e) => this._updateEmail((e as any).target.value)}\n</syntaxhighlight>\n</blockquote>\n\n: That way we can take the value of the event (in this case the key that has been typed). We could test it by writing the '''''_updateEmail()''''' function this way:\n<blockquote>\n<syntaxhighlight lang=\"ts\">\nprivate _updateEmail(email: string){\n    console.log(email);\n}\n</syntaxhighlight>\n</blockquote>\n\n: and then, when we write into the form field, we can open the browser console and verify that the keys that we are typing are being printed in the console:\n\n[[File:onKeyUp.png|1098x1098px|thumb|center|onKeyUp]]\n\n\n* So, we can see that everytime the user enters a new key into the form field, the values of the email and password states are updated. This way, when the user finished to enter the data into the form field, the values of the email and password states will be the whole string the user have entered.\n\n\n* We can then use the '''''_handlerSubmit()''''' and '''''getToken()''''' methods to send the Email and Password to the corresponding REST Web Services in charge of the login (http://localhost:8080/api/v1/auth/login in our case). This REST Web Service will take the Email and Password and will check if the information is valid according to the database. In case the information is valid, http://localhost:8080/api/v1/auth/login will return an '''''auth token'''''.\n\n\n\n* '''Now, let's analyses what happen when we press the submit button:\n:* We go to our Web App in the brower (the explanation here is using GoogleChrome)\n:* We input some data into the Email and Password fields and we press the Submit button\n\n\n:* Let's open the Developer tools (Crl + Shift + i) and go to the Network tap:\n::* Click in the htlm POST request we have just done to http://localhost:8080/api/v1/auth/login\n::* Here we can see the details of the html request. In this section let's go to the Headers tap. Notice in the \u00abRequest Payload\u00bb section that the data entered into the form fields (Email and Password) has been sent:\n\n[[File:Html_request_details.png|1098px|thumb|center|]]\n\n::* We can also see that the request has failed: <span style=\"color:#FF0000\">POST http://localhost:3000/api/v1/auth/login 404 (Not Found)</span>\n::: This is logical because our RES Web service is not running so we cannot reach http://localhost:3000/api/v1/auth/login\n\n\n:* We can also simulate the response from a local file instead of from http://localhost:3000/api/v1/auth/login. Let's create this file:\n<blockquote>\n public/data/login.json\n<syntaxhighlight lang=\"json\">\n{\n    \"token\": \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTQ4NzY0MDIwfQ.4NVMemKu9s_h-r68gy-QKHjBtJSWpYPLjSPBwWGylbY\"\n}\n</syntaxhighlight>\n</blockquote>\n\n:: this file is how the response would look like if it comes from http://localhost:3000/api/v1/auth/login in a real server.\n\n:: We have to make some changes in the '''''getToken()''''' method to be able to simulate the response coming from a local file. In the case of this local file, we will just make a GET request to fetch the data from /data/login.json. Therefore, our '''''getToken()''''' method would be like this:\n<blockquote>\n src/pages/login.tsx\n<syntaxhighlight lang=\"ts\">\n.\n.\n.\nasync function getToken(email: string, password: string){\n    const data = {\n        email: email,\n        password: password\n    }\n    const response = await fetch(\n        \"/data/login.json\",\n        {\n            method: \"GET\",\n            headers: {\n                'Content-type': 'application/json'\n            },\n            // body: JSON.stringify(data) // No body for a GET request\n        }\n    );\n    const json = await response.json();\n    // { token: \"lasflsfooiwerojsdfosjfoijljosdifjosdfijsdfoijoweoierj\" }\n    return json.token;\n}\n.\n.\n.\n</syntaxhighlight>\n</blockquote>\n\n\n:: Now, if we analyse the request after pressing the Submit button, we can see the response of the request, which is the content of the login.json file:\n\n\n[[File:Html_request_details_from_local_file.png|1098px|thumb|center|]]\n\n\n<br />\n===Input validations with Joi===\nhttps://www.npmjs.com/package/joi\n\nhttps://www.npmjs.com/package/@hapi/joi\n\nhttps://www.npmjs.com/package/react-joi-validation\n\n\nWe can do input validations using the same library (joi) that we used in Node.js (Server side):\n src/pages/login.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\nimport * as joi from \"joi\";\n\n\nconst credentialSchema =  {\n    email: joi.string().email().required(),\n    password: joi.string().min(3).max(30).required()\n};\n\n\ninterface LoginProps {\n\n}\n\ninterface LoginState {\n    email: string;\n    password: string\n}\n\n\nexport class Login extends React.Component<LoginProps, LoginState> {\n    public constructor(props: LoginProps){\n        super(props)\n        this.state = {\n            email: \"\",\n            password: \"\"\n        };\n    }\n    public render(){\n        return(\n            <div>\n                {/* We need to call the _renderValidationErrors method inside the render method: */}\n                {this._renderValidationErrors()}\n                <input\n                    type=\"text\"\n                    placeholder=\"Email\"\n                    onKeyUp={(e) => this._updateEmail((e as any).target.value)}\n                />\n                <input\n                    type=\"password\"\n                    placeholder=\"Password\"\n                    onKeyUp={(e) => this._updatePassword((e as any).target.value)}\n                />\n                <button onClick={() => this._handlerSubmit()}>Submit</button>\n            </div>\n        );\n    }\n    private _updateEmail(email: string){\n        // console.log(email);  // We can do this just to verify that the keys that are being typing into the form field are printed in the browser console.\n        this.setState({email: email});\n    }\n    private _updatePassword(password: string){\n        this.setState({password: password});\n    }\n    private _handlerSubmit() {\n        (async () => {\n            await getToken(this.state.email, this.state.password);\n        })();\n    }\n    private _renderValidationErrors(){\n        // joi.validate takes a value and the Schema (validation rule)\n        // In our case, the value is going to be an object with an Email and a Password\n        // It returns a validation object\n        const validationResults = joi.validate({\n            email:   this.state.email,\n            password: this.state.password},\n            credentialSchema);\n            // validationResults has an error property:\n            if (validationResults.error){\n                return <div>\n                    {/* The error has a detail property, whici of type joi.ValidationErrorItem[] \n                        That we have to map into a JSX element: */}\n                    {validationResults.error.details.map(d => <div>{d.message}</div>)}\n                </div>;\n            } else {\n                return <div>OK!</div>;\n            }\n    }\n}\n\n\nasync function getToken(email: string, password: string){\n    const data = {\n        email: email,\n        password: password\n    }\n    const response = await fetch(\n        \"/api/v1/auth/login\",\n        {\n            method: \"POST\",\n            headers: {\n                'Content-type': 'application/json'\n            },\n            body: JSON.stringify(data)\n        }\n    );\n    const json = await response.json();\n    // { token: \"lasflsfooiwerojsdfosjfoijljosdifjosdfijsdfoijoweoierj\" }\n    return json.token;\n}\n</syntaxhighlight>\n\n\n<br />\n\n==Connecting the Front-end and the Back-end==\n\n* In our React project, we need to configure the ''proxy'' property in ''package.json''  according to the domain and port where the back-end is running: '''''\"proxy\": \"http://localhost:8080\",'''''\n\n<blockquote>\n package.json\n<syntaxhighlight lang=\"json\">\n{\n  \"name\": \"myreactapp\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"proxy\": \"http://localhost:8080\",\n  \"dependencies\": {\n    \"@types/jest\": \"24.0.0\",\n    \"@types/joi\": \"^14.3.2\",\n    \"@types/node\": \"10.12.21\",\n\n  .\n  .\n  .\n</syntaxhighlight>\n</blockquote>\n\n\n* Then we need to start both projects: Node.js and React\n\n\n:* To start the Node.js project, we go to the directory and run:\n<blockquote>\n<syntaxhighlight lang=\"shell\">\nnodemon\n</syntaxhighlight>\nThis project is usually configured to run in port 8080.\n\n\nRemember that before running the project, we need to start our ''postgres'' database and define the environment variables:\n<syntaxhighlight lang=\"shell\">\n# To see the Postgres container:\nsudo docker ps -a\n\n# To start the Docker container:\nsudo docker start 3234e2864a8e\n\n# Set environment variables:\nexport DATABASE_HOST=localhost\nexport DATABASE_PORT=5432\nexport DATABASE_DB=twitterclone_db\nexport DATABASE_USER=postgres\nexport DATABASE_PASSWORD=secret\n\nexport AUTH_SECRET=miclaveprivada\n</syntaxhighlight>\n\nIf everything is ok, we'll be able to show all the links created using this url: http://localhost:8080/api/v1/links\n</blockquote>\n\n\n:* Then we go to the React directory and run:\n<blockquote>\n<syntaxhighlight lang=\"shell\">\nnmp run start\n</syntaxhighlight>\nThis project is usually configured to run in port 3000.\n</blockquote>\n\n\n* Let's do a first example in which the React App is going to fetch data using the REST Web Services that we created in the Back-end using Node.js:\n\n: We are going to do a very similar page to to the src/pages/todos.tsx page we previously created (which is taking data from this url: http://jsonplaceholder.typicode.com/todos) but now we are going to fetch data using our REST Web Service responsible to return all the links from our database: http://localhost:8080/api/v1/links:\n\n<blockquote>\n src/pages/mylinks.tsx\n<syntaxhighlight lang=\"ts\">\nimport React from 'react';\n\nimport {Listview2 } from \"../components/listview/listview2\";\n\n\n// We have called it LinkA to avoid confutions with the Link component \n// used in the routing process in index.tsx: import {BrowserRouter, Switch, Route, Link} from 'react-router-dom';\ninterface LinkA {\n    id: number;\n    url: String;\n    title: string;\n    reference_user: {\n        id: number;\n        email: string;\n        password: string;\n    };\n}\n\ninterface MyLinksProps {\n\n}\n\ninterface MyLinksState {\n    linksA: LinkA[] | null;\n}\n\n\nexport class MyLinks extends React.Component<MyLinksProps, MyLinksState> {\n    public constructor(props: MyLinksProps){\n        super(props);\n        this.state = {\n            linksA: null\n        };\n    }\n    public componentDidMount(){\n        (async () => {\n            const data = await getData();\n            this.setState({ linksA: data });\n        })();\n    }\n    public render(){\n        const imgStyle: React.CSSProperties = { width: \"100px\", height: \"100px\"};\n        if (this.state.linksA === null){\n            return <div>Loding...</div>\n        } else {\n            return (<Listview2\n                        items={\n                            this.state.linksA.map((l) => {\n                                // To be able to return a JSX element, the type of\n                                // items have to be JSX.Element[], as was defined in <Listview2>\n                                // If we use <Listview> we have to return a string.\n                                return (\n                                    <div>\n                                        <ul>\n                                            {l.url}\n                                        </ul>\n                                        <ul>\n                                            {l.reference_user.email}\n                                        </ul>\n                                    </div>\n                                );\n                            })\n                        }\n                />\n            );\n        }\n    }\n}\n\nasync function getData(){\n    const response = await fetch(\"/api/v1/links\");\n    const json = await response.json();\n    return json as LinkA[];\n}\n</syntaxhighlight>\n\n<span style=\"color:#FF0000\">'''The url of our REST Web Service have to be entered this way:'''</span> '''''const response = await fetch(\"/api/v1/links\");'''''\n\n<span style=\"color:#FF0000\">'''If we to like this:'''</span> '''''const response = await fetch(\"http://localhost:8080/api/v1/links\");''''' <span style=\"color:#FF0000\">'''we'll have an error'''</span>. Like this it doesn't work because if you have another port we'll be trying to share resources between two different domains, which is not allowed. This is way we had to configure the '''''proxy''''' in the ''package.json'' file, which redirect the request to the correct server.\n\nActually, notice that if we review the details of the html request in the Web Browser > Developer tools (Crl + Shift + i) we'll see that the Request URL is show to be from port 3000 (http://localhost:'''3000'''/api/v1/links) even if our REST Web Service is running in port '''8080'''. That is like this because we are actually sending the request to the '''3000''' but the '''''proxy''''' is redirecting it to the '''8080''':\n\n\n[[File:Html_request_details2.png|1098px|thumb|center|]]\n \n<blockquote>\n\n\n<br />\n\n==Create a Login Form==\n\n* https://react-bootstrap.github.io/components/forms/\n\n\n* https://bootsnipp.com/tags/login?page=3\n\n\n* https://bootsnipp.com/snippets/a6Pdk\n\n\n\n* https://mdbootstrap.com/docs/react/forms/basic/\n\n\n* https://www.youtube.com/watch?v=OWYxMCfcTbY\n* Written tutorial:\n:* https://ipenywis.com/tutorials/Let's-Create-a-Modern-Login-Form-on-React-|-01\n:* https://ipenywis.com/tutorials/Let's-Create-a-Modern-Login-Form-on-React-|-02\n\n\n* https://www.youtube.com/watch?v=XHPL-rX9m-Q\n\n\n* https://codepen.io/Lakston/pen/XjAQdP\n\n\n* https://phoenix-trello.herokuapp.com/sign_in\n\n\n<br />\n\n==Headers- NavBar==\nVery nice: https://codesandbox.io/s/48y8zyz46w?from-embed\n\n\nhttps://react-bootstrap.github.io/components/navbar/\n\nhttps://react-bootstrap.github.io/components/navs/\n\nhttps://www.npmjs.com/package/react-bootstrap\n\nhttps://www.npmjs.com/package/bootstrap-4-react\n\nhttps://www.npmjs.com/package/@types/react-bootstrap\n\nhttps://getbootstrap.com/docs/4.1/examples/\n\n\n'''To make Bootstrap Navbar and Routing working together:'''\n: https://stackoverflow.com/questions/54843302/reactjs-bootstrap-navbar-and-routing-not-working-together\n\n\n<br />\n==Icons==\nhttps://www.npmjs.com/package/react-icons :\n* https://react-icons.netlify.com/#/\n\n\nhttps://mdbootstrap.com/docs/react/content/icons-list/\n* https://mdbootstrap.com/docs/react/components/buttons-social/\n\n\nhttps://material-ui.com/components/icons/\n\n\n<br />\n\n==More about Components - Taken from the React official documentation==\nhttps://reactjs.org/docs/react-component.html\n\nReact lets you define components as classes or functions. Components defined as classes currently provide more features which are described in detail on this page. To define a React component class, you need to extend React.Component:\n\n<syntaxhighlight lang=\"js\">\nclass Welcome extends React.Component {\n  render() {\n    return <h1>Hello, {this.props.name}</h1>;\n  }\n}\n</syntaxhighlight>\n\nThe only method you must define in a React.Component subclass is called render(). All the other methods described on this page are optional.\n\n\n<br />\n===Components and Props===\nPara probar c\u00f3digos: https://codepen.io/pen\n\nhttps://reactjs.org/docs/components-and-props.html\n\nComponents let you split the UI into independent, reusable pieces, and think about each piece in isolation. This page provides an introduction to the idea of components.\n\nConceptually, components are like JavaScript functions. They accept arbitrary inputs (called \"props\") and return React elements describing what should appear on the screen.\n\n\n<br />\n====Function and Class Components====\nThe simplest way to define a component is to write a JavaScript function:\n<syntaxhighlight lang=\"js\">\nfunction Welcome(props) {\n  return <h1>Hello, {props.name}</h1>;\n}\n</syntaxhighlight>\n\nThis function is a valid React component because it accepts a single '''''props''''' (which stands for properties) object argument with data and returns a React element. We call such components '''''function components''''' because they are literally JavaScript functions.\n\n\nYou can also use an ES6 class to define a component:\n<syntaxhighlight lang=\"js\">\nclass Welcome extends React.Component {\n  render() {\n    return <h1>Hello, {this.props.name}</h1>;\n  }\n}\n</syntaxhighlight>\n\n\nThe above two components are equivalent from React's point of view.\n\n\nClasses have some additional features that we will discuss in the next sections. Until then, we will use function components for their conciseness.\n\n\n<br />\n====Rendering a Component====\nPreviously, we only encountered React elements that represent DOM tags:\n<syntaxhighlight lang=\"js\">\nconst element = <div />;\n</syntaxhighlight>\n\nHowever, elements can also represent user-defined components:\n<syntaxhighlight lang=\"js\">\nconst element = <Welcome name=\"Sara\" />;\n</syntaxhighlight>\n\nWhen React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object \"props\".\n\nFor example, this code renders \"Hello, Sara\" on the page:\n<syntaxhighlight lang=\"js\">\nfunction Welcome(props) {\n  return <h1>Hello, {props.name}</h1>;\n}\n\nconst element = <Welcome name=\"Sara\" />;\nReactDOM.render(\n  element,\n  document.getElementById('root')\n);\n</syntaxhighlight>\n\nLet's recap what happens in this example:\n* We call '''''ReactDOM.render()''''' with the '''''<nowiki> <Welcome name=\"Sara\" /> </nowiki>''''' element.\n* React calls the '''''Welcome''''' component with '''''{name: 'Sara'}''''' as the props.\n* Our '''''Welcome''''' component returns a '''''<nowiki><h1>Hello, Sara</h1></nowiki>''''' element as the result.\n* React '''''DOM''''' efficiently updates the DOM to match '''''<nowiki><h1>Hello, Sara</h1></nowiki>'''''.\n\n\nNote: Always start component names with a capital letter.\nReact treats components starting with lowercase letters as DOM tags. For example, '''''<nowiki><div /></nowiki>''''' represents an '''''HTML div''''' tag, but '''''<Welcome />''''' represents a component and requires Welcome to be in scope.\nTo learn more about the reasoning behind this convention, please read JSX In Depth.\n\n\n<br />\n====Composing Components====\nComponents can refer to other components in their output. This lets us use the same component abstraction for any level of detail. A button, a form, a dialog, a screen: in React apps, all those are commonly expressed as components.\n\nFor example, we can create an App component that renders Welcome many times:\n\n<syntaxhighlight lang=\"js\">\nfunction Welcome(props) {\n  return <h1>Hello, {props.name}</h1>;\n}\n\nfunction App() {\n  return (\n    <div>\n      <Welcome name=\"Sara\" />\n      <Welcome name=\"Cahal\" />\n      <Welcome name=\"Edite\" />\n    </div>\n  );\n}\n\nReactDOM.render(\n  <App />,\n  document.getElementById('root')\n);\n</syntaxhighlight>\n\n\n<br />\n====Extracting Components====\nDon\u2019t be afraid to split components into smaller components.\n\nFor example, consider this Comment component:\n\n<syntaxhighlight lang=\"js\">\nfunction Comment(props) {\n  return (\n    <div className=\"Comment\">\n      <div className=\"UserInfo\">\n        <img className=\"Avatar\"\n          src={props.author.avatarUrl}\n          alt={props.author.name}\n        />\n        <div className=\"UserInfo-name\">\n          {props.author.name}\n        </div>\n      </div>\n      <div className=\"Comment-text\">\n        {props.text}\n      </div>\n      <div className=\"Comment-date\">\n        {formatDate(props.date)}\n      </div>\n    </div>\n  );\n}\n</syntaxhighlight>\n\n\nThis component can be tricky to change because of all the nesting, and it is also hard to reuse individual parts of it. Let's extract a few components from it.\n\nFirst, we will extract Avatar:\n<syntaxhighlight lang=\"js\">\nfunction Avatar(props) {\n  return (\n    <img className=\"Avatar\"\n      src={props.user.avatarUrl}\n      alt={props.user.name}\n    />\n  );\n}\n</syntaxhighlight>\n\nThe Avatar doesn't need to know that it is being rendered inside a Comment. This is why we have given its prop a more generic name: user rather than author.\n\nWe recommend naming props from the component\u2019s own point of view rather than the context in which it is being used.\n\n\nWe can now simplify Comment a tiny bit:\n<syntaxhighlight lang=\"js\">\nfunction Comment(props) {\n  return (\n    <div className=\"Comment\">\n      <div className=\"UserInfo\">\n        <Avatar user={props.author} />\n        <div className=\"UserInfo-name\">\n          {props.author.name}\n        </div>\n      </div>\n      <div className=\"Comment-text\">\n        {props.text}\n      </div>\n      <div className=\"Comment-date\">\n        {formatDate(props.date)}\n      </div>\n    </div>\n  );\n}\n</syntaxhighlight>\n\n\nNext, we will extract a UserInfo component that renders an Avatar next to the user's name:\n<syntaxhighlight lang=\"js\">\nfunction UserInfo(props) {\n  return (\n    <div className=\"UserInfo\">\n      <Avatar user={props.user} />\n      <div className=\"UserInfo-name\">\n        {props.user.name}\n      </div>\n    </div>\n  );\n}\n</syntaxhighlight>\n\n\nThis lets us simplify Comment even further:\n<syntaxhighlight lang=\"js\">\nfunction Comment(props) {\n  return (\n    <div className=\"Comment\">\n      <UserInfo user={props.author} />\n      <div className=\"Comment-text\">\n        {props.text}\n      </div>\n      <div className=\"Comment-date\">\n        {formatDate(props.date)}\n      </div>\n    </div>\n  );\n}\n</syntaxhighlight>\n\n\nExtracting components might seem like grunt work at first, but having a palette of reusable components pays off in larger apps. A good rule of thumb is that if a part of your UI is used several times (Button, Panel, Avatar), or is complex enough on its own (App, FeedStory, Comment), it is a good candidate to be a reusable component.\n\n\n<br />"
                    }
                ]
            },
            "1412": {
                "pageid": 1412,
                "ns": 0,
                "title": "React 2",
                "revisions": [
                    {
                        "contentformat": "text/x-wiki",
                        "contentmodel": "wikitext",
                        "*": "Creo que voy a tener que comprar este curso: https://www.udemy.com/course/the-nextjs-13-bootcamp-the-complete-developer-guide/\n\nNext.js framework: \n* https://nextjs.org/learn/foundations/about-nextjs\n* https://beta.nextjs.org/docs\n\n\n<br />\n==Install React and Create a react project==\n'''Install React:'''\n\nInstall Node.js and npm:\n<syntaxhighlight lang=\"shell\">\n# Add the Node.js repository:\ncurl -sL https://deb.nodesource.com/setup_lts.x | sudo -E bash -\n\nsudo apt install -y nodejs\nsudo apt install -y npm\nsudo npm install -g create-react-app\nsudo npm install -g create-next-app    # Next.js es el primer frameworks propuesto en la documentacion\n\nnode -v\nnpm -v\ncreate-react-app -V   # Capital V\ncreate-next-app -V\n</syntaxhighlight>\n\n\n<br />\n'''Create a New React Project - Official documentation''':<br />\n<span style=\"color:green; font-weight:bold\">If you want to build a new app or a new website fully with React, we recommend picking one of the React-powered frameworks popular in the community.<br />\nCan I use React without a framework?<br />\nYou can definitely use React without a framework\u2014that\u2019s how you\u2019d use React for a part of your page. However, if you\u2019re building a new app or a site fully with React, we recommend using a framework. <br />\nHere\u2019s why... </span> https://react.dev/learn/start-a-new-react-project\n\n<syntaxhighlight lang=\"shell\">\nnpx create-react-app name_project  # React without a framework\nnpx create-next-app  name_project  # Next.js es el primer frameworks propuesto en la documentacion\n</syntaxhighlight>\n\n\nThen, to start the app:\n<syntaxhighlight lang=\"shell\">\nnpm start\n</syntaxhighlight>\n\n\n<br />\n\n==Templates==\nFrom the Next documentation there are some free templates: https://nextjs.org/learn/foundations/about-nextjs\n\nThis page list some good free templates: 11 Best Free Next.js Dashboard Admin Templates: https://medevel.com/11-nextjs-dashboard/\n\n\nThere are also some very good paid templates (don't know if call them templetes or compleate webb apps). The best I've seen so far are:\n\n* https://adminmart.com/\n:* https://modernize-nextjs.adminmart.com/ \n: Este tiene versiones de NestJS and React. Creo que solo en TS\n: Free version:\n:* https://adminmart.com/product/modernize-free-nextjs-admin-template/?ref=5\n:* https://github.com/adminmart/Modernize-Nextjs-Free\n\n\n* https://berrydashboard.io/\n: Este tambien est\u00e1 muy bueno y el paquete de 129\u20ac incluye version en React JS, React TS, NextJS JS, NextJS TS and others\n\n\n* https://github.com/themeselection/materio-mui-react-nextjs-admin-template-free\n: Este parece que esta en both JS and TypeScript. They ave free en Pro versions\n\n\n* https://www.wrappixel.com/templates/ample-nextjs-admin-dashboard/\n\n\n<br />\n\n==JSX to JS==\nTools that translate JSX into JS: https://babeljs.io/repl\n\n\n<br />\n\n==React developer tools Google Chrome extension==\nTake a looks at some of the basic functionalities of the React developer tools Google Chrome extension at:\nhttps://www.udemy.com/course/react-redux/learn/lecture/34693592#overview\n\n\n<br />\n\n==CSS Libraries==\n* https://bulma.io/\n npm install bulma\n\n\n<br />\n==Props==\n...\n\n\n\n<br />\n==Events==\nhttps://react.dev/learn/responding-to-events\n\nhttps://legacy.reactjs.org/docs/events.html\n\n\n<br />\n==Modern React with Redux Udemy course==\nhttps://www.udemy.com/course/react-redux/\n\n\nA good overview explanation of how React works can be found on the '''critical questions/core concepts''' lectures of the present course. Here the link to the lecture:\n* https://www.udemy.com/course/react-redux/learn/lecture/34693340#overview\n\n\n<br />\n===First app===\nhttps://codesandbox.io/s/react-forked-m5bz37\n\n\n<br />"
                    }
                ]
            }
        }
    }
}