#TIL
Notes taken from Quick Start - React
This is by no means a comprehensive #TIL of the react.dev’s quick start page. Rather, I took notes on parts that I wasn’t clear on or parts that I’ve learned for the first time.
The code that I’m using here is from the react.dev’s site; therefore, credit belongs to them, unless stated otherwise.
JSX:
- Allows you to put markup (e.g. HTML) into JavaScript.
- To escape back into JavaScript within markup, use
{}
like so:
return (
<h1>
{user.name}
</h1>
);
- You also use the same curly braces when putting JavaScript variables or code into JSX attributes, like so:
return (
<img
className="avatar"
src={user.imageUrl}
/>
);
- Cool Note: Within curly braces, you can also combine JS variables with strings of text
export const Profile() => {
return (
<section>
<h1>{user.name}</h1>
<img
className="profileAvatar"
src={user.avatarUrl}
alt={'Photo of ' + user.name}
style={{
width: 100px,
height: 100px,
}}
/>
</section>
);
}
- the
style
attribute has two curly braces because the first outer pair is to “escape into JavaScript” and the second is representing the{}
object
Conditional rendering:
- Ah, I can use if and else statements, just within the component but above the return statement..! I was so used to using ternary operators within the JSX code that I didn’t know how to utilize the classic
if
andelse
statements.
let content;
if (isLoggedIn) {
content = <AdminPanel />;
} else {
content = <LoginForm />;
}
return (
<div>
{content}
</div>
);
Hooks:
- functions in React that start with
use
are called Hooks. - Can only call Hooks at the top of components.
Sharing data between components
- If you have information that needs to be shared ‘globally’ across different components, you need to declare the state usign
useState()
at the parent scope and pass the state and the state modifier function down to its children components. - You pass them down using JSX curly braces as attributes, like so below:
- These are called PROPS!
export default function MyApp() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Counters that update together</h1>
<MyButton count={count} onClick={handleClick} />
<MyButton count={count} onClick={handleClick} />
</div>
);
}
- If you want the child components to utilize the props passed down, you have to pass
props
as a parameter, or also use destructuring syntax.