Sử dụng JSX(Javascript Syntax Extension) giúp bạn dễ hình dung các React element và dễ code hơn. Nó gần giống như bạn viết HTML trong JS.
const ui = <h1 id="greeting">Hey there</h1>
// ↓ ↓ ↓ ↓ compiles to ↓ ↓ ↓ ↓
const ui = React.createElement('h1', {id: 'greeting', children: 'Hey there'})
Bởi vì JSX không phải là Javascript nên bạn phải cần một trình biên dich để dich từ JSX syntax sang JS. Đó là Babel. Nếu bạn muốn playground với JSX bạn có thể vào đây.
Chuyển createElement sang JSX
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@17.0.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17.0.0/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.12.4/babel.js"></script>
<script type="module">
// 🐨 thay `type="module"`
// bằng `type="text/babel"` so babel có thể compile code của bạn
// 🐨 sử dụng JSX để tạo các element sau!
const element = React.createElement('div', {
className: 'container',
children: 'Hello World',
})
// 💰 Trong JSX bạn sẽ sử dung className thay cho class như trong HTML
// Chi tiết:
// https://reactjs.org/docs/dom-elements.html#differences-in-attributes
ReactDOM.render(element, document.getElementById('root'))
</script>
</body>
Hãy tự làm trước khi xem đáp án nhé. Học phải đi đôi với hành nào! Boom!!! Đáp án:
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@17.0.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17.0.0/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.12.4/babel.js"></script>
<script type="text/babel">
const element = <div className="container">Hello World</div>
ReactDOM.render(element, document.getElementById('root'))
</script>
</body>
Interpolate giá trị trong JSX
const className = 'container'
const children = 'Hello World'
const element = <div className="hmmm">how do I make this work?</div>
//Bạn phải render được className từ biến và content cho thẻ div
const className = 'container'
const children = 'Hello World'
const element = <div className={className}>{children}</div>
Giả sử bạn có một props object như sau:
const children = 'Hello World'
const className = 'container'
const props = {children, className}
const element = <div /> // Bạn làm sao để apply props và element này?
const children = 'Hello World'
const className = 'container'
const props = {children, className}
const element = <div {...props} />
Chúc bạn làm bài tốt!!!
thaunguyen.com via Epic React by Kent C.Dodds