Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

ReactJs - Environment Setup

Cài đặt môi trường

Đầu tiên các bạn cần cài đặt NodeJS để tạo môi trường chạy React.

Tạo Project

Để tạo project ReactJS, chúng ta sẽ sử dụng tool hỗ trợ có sẵn là create-react-app. Chạy lệnh sau để cài đặt:

Code Block
npm install -g create-react-app

Sau đó, vào thự mục nơi bạn muốn lưu project và chạy lệnh sau để tạo project:

Code Block
create-react-app my-app

Dòng lệnh trên sẽ tạo cho sẽ tạo cho ta 1 project tên là my-app và install các module và lib cần thiết cho chúng ta.

Trong thư mục src của project mới tạo sẽ có 3 file chúng ta cần quan tâm:

src/App.js

Code Block
languagejs
import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            Hello World!!!
         </div>
      );
   }
}
export default App;

Đây là React component đầu tiên của chúng ta, chúng ta sẽ tìm hiểu component là gì ở các phần sau, component này là App sẽ render Hello World ra màn hình.

src/index.js

Code Block
languagejs
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App />, document.getElementById('root'));

File này sẽ làm nhiệm vụ render component App ở trên vào 1 thẻ html với id "root" ở trong fileindex.html

public/index.html

Code Block
languagehtml
<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>

Đây là file HTML chính của ta, tất cả component sẽ được render ra đây.

Chạy thử project

Các bạn mở terminal lên, vào thự mục root của project và gõ lệnh:

Code Block
npm start