import { render } from 'react';
function NumberList({ numbers }) {
return (
<ul>
{numbers.map(
(number) => <li>{number}</li>
)}
</ul>
);
}
// Usage
const numbers = [1, 2, 3, 4, 5];
function App() {
return <NumberList numbers={numbers} />;
}
render(<App />)
body {
padding: 16px;
font-size: 24px;
}
h1 {
font-size: 32px;
}
ul {
padding-left: 30px;
}
import React, { render } from 'react';
function NumberList({ items }) {
return (
<ul>
{items.map(
(item) => <li>{number}</li>
)}
</ul>
);
}
// Usage
const numbers = [1, 2, 3, 4, 5];
function App() {
return <NumberList items={numbers} />;
}
render(<App />)
body {
padding: 16px;
font-size: 24px;
}
h1 {
font-size: 32px;
}
ul {
padding-left: 30px;
}
import { render } from 'react';
const todos = [
{ id: 1, text: "Some Todo" },
{ id: 2, text: "Other Todo" }
];
function ToDoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}
// Usage
function App() {
return <ToDoList todos={todos} />;
}
render(<App />)
body {
padding: 16px;
font-size: 24px;
}
h1 {
font-size: 32px;
}
ul {
padding-left: 30px;
}
import { useState } from "react";
let uid = 3;
// noprotect
function Item({ name, id }) {
return (
<div>
<label>{name}: </label>
<input
type='text'
id={id}
/>
</div>
)
}
function App() {
const [state, setState] = useState([
{name: '1', id: 1},
{name: '2', id: 2}
])
function addItem() {
const id = uid ++;
setState(
[ {name: id.toString(), id} , ...state]
);
}
return (
<div>
<b>How to use: </b>
First write something in the inputs. Then hit <em>Add item</em> and see what happens.
<hr/>
<button className='btn btn-primary' onClick={addItem}><b>Add item</b> to the beginning of the list</button>
<h3>Dangerous <code>key=index</code></h3>
<form className="form-horizontal">
{state.map((todo, index) =>
<Item
name={todo.name}
id={'d_' + todo.id}
key={index}
/>
)}
</form>
<hr />
<h3>Better <code>key=id</code></h3>
<form className="form-horizontal">
{state.map((todo) =>
<Item
name={todo.name}
id={'s_' + todo.id}
key={todo.id} />
)}
</form>
</div>
)
}
render(<App />)
body {
padding: 16px;
font-size: 24px;
}
button {
padding: 8px;
background: salmon;
font-size: 18px;
}
h1 {
font-size: 32px;
}
hr {
margin: 16px 0px;
}
function ArticleList({ articles }) {
if (!articles.length) {
return <p>No articles available.</p>;
}
return (
<ul>
{articles.map((article) =>
<li key={article.id}>
{article.title}
</li>
)}
</ul>
);
}
// Usage
function App() {
return <ArticleList articles={[]} />;
}
render(<App />)
body {
padding: 16px;
font-size: 24px;
}
h1 {
font-size: 32px;
}
import { Fragment } from 'react';
function TagList({ tags }) {
return (
<>
{tags.map((tag) =>
<Fragment key={tag.id}>
{tag.name}, {' '}
</Fragment>
)}
</>
);
}
// Usage
function App() {
return <TagList tags={[
{ id: 1, name: '#Tag1'},
{ id: 2, name: '#Tag2'}
]} />;
}
render(<App />)
body {
padding: 16px;
font-size: 24px;
}
h1 {
font-size: 32px;
}