What is React?
React is a JavaScript open-source library for front end developing.
3 Characteristics of React
JSX
JavaScript XML (not a string or HTML)
Developed from JavaScript to make an element in React.
It's not possible to use JSX directly to run a browser, you need to use Babel to convert a JSX code into a JavaScript code.
Unlike DOM, you need only a CSS & JSX file to develop a web application.
JSX looks like an HTML.
JSX improves the simplicity of developing, which is a big reason you need to learn JSX.
Rule #1:
When you want to write an element in JSX you have to use an opening & closing tag
Rule#2:
<div class="greeting>Hello!</div> WRONG!
<div className="greeting">Hello!</div> CORRECT!
Rule#3:
Use {}(brace) when using JavaScript in JSX.
function App() {
const name = 'Josh Perez';
return (
<div>
Hello, {name}!
</div>
);
}
Rule#4:
When writing a React element use capitalized letter.
All capitalized component is JSX is called a custom component.
Wrong Example:
function hello() {
return <div>Hello!</div>;
}
function HelloWorld() {
return <hello/>;
}
Correct Example:
function Hello() {
return <div>Hello!</div>;
}
function HelloWorld() {
return <Hello/>;
}
Rule#5:
Conditional rendering should use the ternary operator, not the 'if' statement
<div>
{
(1+1 === 2) ? (<p>answer</p>) : (<p>false</p>)
}
</div>
Rule#6:
Whne showing multitple HTML elements in React, use the map() function. When using the map function you must put the "key" JSX property.
const posts = [
{id: 1, title: 'Hello WOrld', content: 'Welcome to learning React!'},
{id: 2, title: 'Installation', content: 'You can install React from npm.'}
];
function Blog() {
const content = posts.map((post) =>
<div key = {post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
</div>
);
return (
<div>
{content}
</div>
);
}