import React from "react"
import ReactDOM from "react-dom"
// Objective: Fill in the boilerplate React code required to render an
// unordered list (<ul>) to the page. The list should contain 3 list items
// (<li>) with anything in them you want.
// HINTS:
// import the libraries you need first
// use one of the libraries to render some JSX to the page
ReactDOM.render(<div><h1>Hello world</h1></div>, document.getElementById("root"));
Functional component
function MyApp(){ //--CamelCase --FirstCapitalLetter
return //jsx
(
<ul>
<li>1</li>
<li>2</li>
</ul>
)
}
ReactDom.render(
<MyApp />,
document.getElementById("root")
)
Good practice
- Each file contains only one component
- CamelCase
- FirstCapitalLetter
- Parentheses in return
Exportar componente
export default MyInfo
In JSX, you can't use the word class! You have to use className instead:
<h1 className="big">Hey</h1>
This is because JSX gets translated into JavaScript, and class is a reserved word in JavaScript.
In JSX, you have to include the slash. If you write a self-closing tag in JSX and forget the slash, you will raise an error:
Fine in JSX: <br /> NOT FINE AT ALL in JSX: <br>
import React from 'react';
import ReactDOM from 'react-dom';
// Write code here:
ReactDOM.render(
<h1>2 + 3</h1>,
document.getElementById('app')
);
Add a pair of curly braces to the code from last exercise, so that your JSX expression looks like this:
<h1>{2 + 3}</h1>
Everything inside of the curly braces will be treated as regular JavaScript.
The curly braces themselves won't be treated as JSX nor as JavaScript. They are markersthat signal the beginning and end of a JavaScript injection into JSX,
import React from 'react';
import ReactDOM from 'react-dom';
// Write code here:
const math = (
<h1>2 + 3 = {2 + 3}</h1>
)
ReactDOM.render(
math,
document.getElementById('app')
);
import React from 'react';
import ReactDOM from 'react-dom';
const theBestString = 'tralalalala i am da best';
ReactDOM.render(<h1>{theBestString}</h1>, document.getElementById('app'));
When writing JSX, it's common to use variables to set attributes.
Here's an example of how that might work:
// Use a variable to set the `height` and `width` attributes:const sideLength = "200px"; const panda = ( <img src="images/panda.jpg" alt="panda" height={sideLength} width={sideLength} /> );
Object properties are also often used to set attributes:
const pics = { panda: "http://bit.ly/1Tqltv5", owl: "http://bit.ly/1XGtkM3", owlCat: "http://bit.ly/1Upbczi" }; const panda = ( <img src={pics.panda} alt="Lazy Panda" /> ); const owl = ( <img src={pics.owl} alt="Unimpressed Owl" /> ); const owlCat = ( <img src={pics.owlCat} alt="Ghastly Abomination" /> );
import React from 'react'; import ReactDOM from 'react-dom'; function makeDoggy(e) { // Call this extremely useful function on an <img>. // The <img> will become a picture of a doggy. e.target.setAttribute('src', 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-puppy.jpeg'); e.target.setAttribute('alt', 'doggy'); } const kitty = ( <img onClick={makeDoggy} src="https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-kitty.jpg" alt="kitty" /> ); ReactDOM.render(kitty, document.getElementById('app'));
Note that in HTML, event listener names are written in all lowercase, such as onclick or onmouseover. In JSX, event listener names are written in camelCase, such as onClick or onMouseOver.
Formas de condicional if:
import React from 'react';
import ReactDOM from 'react-dom';
let message;
if (user.age >= drinkingAge) {
message = (
<h1>
Hey, check out this alcoholic beverage!
</h1>
);
} else {
message = (
<h1>
Hey, check out these earrings I got at Claire's!
</h1>
);
}
ReactDOM.render(
message,
document.getElementById('app')
);
Here's how you might use the ternary operator in a JSX expression:
const headline = ( <h1> { age >= drinkingAge ? 'Buy Drink' : 'Do Teen Stuff' } </h1> );
&& works best in conditionals that will sometimes do an action, but other times do nothing at all.
Here's an example:
const tasty = ( <ul> <li>Applesauce</li> { !baby && <li>Pizza</li> } { age > 15 && <li>Brussels Sprouts</li> } { age > 20 && <li>Oysters</li> } { age > 25 && <li>Grappa</li> }
{ true && <li>Grappa</li> } //printa
</ul> );
Every time that you see && in this example, either some code will run, or else no code will run.
import React from 'react';
import ReactDOM from 'react-dom';
function coinToss () {
// Randomly return either 'heads' or 'tails'.
return Math.random() < 0.5 ? 'heads' : 'tails';
}
const pics = {
kitty: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-kitty.jpg',
doggy: 'https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-puppy.jpeg'
};
const img = <img src={pics[coinToss() === 'heads' ? 'kitty' : 'doggy']} />;
ReactDOM.render(
img,
document.getElementById('app')
);
const strings = ['Home', 'Shop', 'About Me']; const listItems = strings.map(string => <li>{string}</li>);<ul>{listItems}</ul>
In the above example, we start out with an array of strings. We call .map() on this array of strings, and the .map() call returns a new array of <li>s.
When you make a list in JSX, sometimes your list will need to include something called keys:
<ul> <li key="li-01">Example1</li> <li key="li-02">Example2</li> <li key="li-03">Example3</li> </ul>
A key is a JSX attribute. The attribute's name is key. The attribute's value should be something unique, similar to an id attribute.
keys don't do anything that you can see! React uses them internally to keep track of lists. If you don't use keys when you're supposed to, React might accidentally scramble your list-items into the wrong order.
A list needs keys if either of the following are true:
1. The list-items have memory from one render to the next. For instance, when a to-do list renders, each item must "remember" whether it was checked off. The items shouldn't get amnesia when they render.
2. A list's order might be shuffled. For instance, a list of search results might be shuffled from one render to the next.
If neither of these conditions are true, then you don't have to worry about keys. If you aren't sure then it never hurts to use them!
import React from 'react';
import ReactDOM from 'react-dom';
const people = ['Rowe', 'Prevost', 'Gare'];
const peopleLis = people.map((person,i) =>
// expression goes here:
<li key={'person_'+i}>{person}</li>
);
// ReactDOM.render goes here:
ReactDOM.render(<ul>{peopleLis}</ul>, document.getElementById('app'))
The following JSX expression:
const h1 = <h1>Hello world</h1>;
can be rewritten without JSX, like this:
const h1 = React.createElement( "h1", null, "Hello, world" );
When a JSX element is compiled, the compiler transforms the JSX element into the method that you see above: React.createElement(). Every JSX element is secretly a call to React.createElement().
What's a component?
A component is a small, reusable chunk of code that is responsible for one job. That job is often to render some HTML.
Take a look at the code below. This code will create and render a new React component:
import React from 'react'; import ReactDOM from 'react-dom'; class MyComponentClass extends React.Component { render() { return <h1>Hello world</h1>; } }; ReactDOM.render( <MyComponentClass />, document.getElementById('app') );
This line of code creates a new variable. That variable's name is React, and its value is a particular, imported JavaScript object:
// create a variable named React:import React from 'react'; // evaluate this variable and get a particular, imported JavaScript object:React // { imported object properties here... }
This imported object contains methods that you need in order to use React. The object is called the React library.
To clarify: the DOM is used in React applications, but it isn't part of React. After all, the DOM is also used in countless non-React applications. Methods imported from 'react' are only for pure React purposes, such as creating components or writing JSX elements.
To make a component class, you use a base class from the React library: React.Component.
React.Component is a JavaScript class. To create your own component class, you must subclassReact.Component. You can do this by using the syntax class YourComponentNameGoesHere extends React.Component {}.