November 2019
Amsul Naeem
twitter.com/amsul_
slides.com/amsul
React uses JavaScript & HTML to keep your application UI in sync with your application state.
Elements
Elements
<div>Hi there!</div>
const element = <div>Hi there!</div>
Note the assignment
Attributes
<div id="Title">Hi there!</div>
Props (short for properties)
const element = <div id='Title'>Hi there!</div>
Rendering & Updates
Rendering & Updates
JSX !== JavaScript
&& JSX !== HTML
JSX is an additional syntax on top of JavaScript to mimic HTML.
JSX compiles to JavaScript in a build step.
var element = React.createElement("div", null, "Hi there!");
const element = <div>Hi there!</div>
function Component() {
return <div>Hi there!</div>
}
Components encapsulate logic & markup to be reused and return the composed element to be rendered.
Recreate form with pre-filled values:
Starting point:
lesson-03
directoryfunction Component() {
// Create some state..
const handleButtonClick = () => {
// Do something to the state..
}
// Use the state to show the ### count
return <button onClick={handleButtonClick}>Clicked ### times!</button>
}
function Component() {
const [clicked, setClicked] = React.useState(0)
const handleButtonClick = () => {
// Do something to the state..
}
// Use the state to show the ### count
return <button onClick={handleButtonClick}>Clicked ### times!</button>
}
function Component() {
const [clicked, setClicked] = React.useState(0)
const handleButtonClick = () => {
setClicked(clicked + 1)
}
// Use the state to show the ### count
return <button onClick={handleButtonClick}>Clicked ### times!</button>
}
function Component() {
const [clicked, setClicked] = React.useState(0)
const handleButtonClick = () => {
setClicked(clicked + 1)
}
return <button onClick={handleButtonClick}>Clicked {clicked} times!</button>
}
Props are used to:
useState()
useEffect()
use*
Refactor previous exercise with state & handlers:
Using if
statements
Using &&
conditionals
Using ternary (cond ? a : b
) operators
function Component({ someCondition }) {
if (someCondition) {
return <div>Condition met</div>
}
return <div>Condition not met</div>
}
function Component({ someCondition }) {
return (
<div>
<div>Some content</div>
{someCondition && <div>Condition met</div>}
</div>
)
}
function Component({ someCondition }) {
return (
<div>
{someCondition ? <div>Condition met</div> : <div>Condition not met</div>}
</div>
)
}
function Component() {
const list = [
/*list of items*/
]
return (
<ul>
{list.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
)
}
function ParentComponent() {
const [someCondition, setSomeCondition] = React.useState(false)
if (someCondition) {
return <SubComponentOne />
}
return <SubComponentTwo />
}
Read “Thinking in React”:
November 2019
Amsul Naeem
twitter.com/amsul_
slides.com/amsul