Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Arrays lesson #2136

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
4 changes: 2 additions & 2 deletions src/content/lesson/context-api.es.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,6 @@ return <div>

## Prueba el código en vivo

<iframe src="https://codesandbox.io/embed/w75wq6v01k?fontsize=14&hidenavigation=1&theme=dark" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<iframe src="https://replit.com/@4GeeksAcademy/Demo-Context-API?embed=true&run=true#src/index.jsx" style="width:100%; height:500px; border:0; border-radius: 4px;"></iframe>

<div align="right"><small><a href="https://codesandbox.io/s/w75wq6v01k?from-embed">Haz clic aquí para abrir el demo en una nueva ventana</a></small></div>
<div align="right"><small><a href="https://replit.com/@4GeeksAcademy/Demo-Context-API?embed=true&run=true#src/index.jsx">Haz clic aquí para abrir el demo en una nueva ventana</a></small></div>
68 changes: 34 additions & 34 deletions src/content/lesson/context-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ People say that React.js makes the easy stuff hard and the hard stuff easy. It's

3. [Redux](https://redux.js.org/)?? Overkill.

### The Context API is here to solve some of those conundrums by:
### The Context API is here to solve some of those conundrums by

1. Centralizing a global application state: Instead of being limited to local states on views, you can now share data on one central component and spread to its inner components (children, grandchildren and so forth). The centralized state is called **store**, and we can spread it by using the **Context.Provider**.

Expand Down Expand Up @@ -55,7 +55,7 @@ We must split the **store** from the **actions** and the **views** (components)

Ok, after a couple of hours to make the context API implementation simpler without using bindings... this is what I got in 5 simple steps!:

- **Step 1 (Create the context)**: This step has almost no logic, just call the `createContext` function from React. That object will be shared within all the consumers during the application's lifetime, it will contain the application **store** and **actions**.
+ **Step 1 (Create the context)**: This step has almost no logic, just call the `createContext` function from React. That object will be shared within all the consumers during the application's lifetime, it will contain the application **store** and **actions**.

*AppContext.js*

Expand All @@ -67,11 +67,12 @@ import React from 'react';
const AppContext = React.createContext(null);
```

- **Step 2 (Store and Actions)**: Create a `ContextWrapper` component which will be used to pass the context (step 1) to the Consumers. The `ContextWrapper`'s state is where we declare our initial *global state*, which includes the data (store) and the functions (actions).
+ **Step 2 (Store and Actions)**: Create a `ContextWrapper` component which will be used to pass the context (step 1) to the Consumers. The `ContextWrapper`'s state is where we declare our initial *global state*, which includes the data (store) and the functions (actions).

> Note that we have to export both `AppContext` and `ContextWrapper`.

*AppContext.js*

```js
// Step 2: Create a ContextWrapper component that has to be the parent of every consumer

Expand All @@ -80,22 +81,22 @@ import React, { useState } from 'react';
export const AppContext = React.createContext(null);

export const ContextWrapper = (props) => {
const [ store, setStore ] = useState({
todos: ["Make the bed", "Take out the trash"]
});
const [ actions, setActions ] = useState({
addTask: title => setStore({ ...store, todos: store.todos.concat(title) })
});
return (
<AppContext.Provider value={{ store, actions }}>
{props.children}
</AppContext.Provider>
);
const [ store, setStore ] = useState({
todos: ["Make the bed", "Take out the trash"]
});
const [ actions, setActions ] = useState({
addTask: title => setStore({ ...store, todos: store.todos.concat(title) })
});
return (
<AppContext.Provider value={{ store, actions }}>
{props.children}
</AppContext.Provider>
);
}
```

- **Step 3 (Views)**: Now your main component can be wrapped inside `ContextWrapper` so that all child components will have access to the **Context**. For this quick example, we will be using the `<TodoList />` component as our main component (the declaration is on the last step).
+ **Step 3 (Views)**: Now your main component can be wrapped inside `ContextWrapper` so that all child components will have access to the **Context**. For this quick example, we will be using the `<TodoList />` component as our main component (the declaration is on the last step).

*index.js*

Expand All @@ -109,15 +110,15 @@ import { ContextWrapper } from 'path/to/AppContext.js';
import TodoList from 'path/to/TodoList';

const MyView = () => (
<ContextWrapper>
<TodoList />
</ContextWrapper>
);
<ContextWrapper>
<TodoList />
</ContextWrapper>
);

ReactDOM.render(<MyView />, document.querySelector("#app"));
```

- **Step 4**: Now we can create the `TodoList` component, knowing that we can use `useContext()` hook to read the store from the **global state** (no props necessary).
+ **Step 4**: Now we can create the `TodoList` component, knowing that we can use `useContext()` hook to read the store from the **global state** (no props necessary).

In this case, the component will render the to-do's and also be able to add new tasks to the list.

Expand All @@ -128,21 +129,21 @@ import React, { useContext } from 'react';
import { AppContext } from 'path/to/AppContext.js';

export const TodoList = () => {
const context = useContext(AppContext);
return <div>
{context.store.todos.map((task, i) => (<li key={i}>{task}</li>))}
<button onClick={() => context.actions.addTask("I am the task " + context.store.todos.length)}> + add </button>
</div>
const context = useContext(AppContext);
return <div>
{context.store.todos.map((task, i) => (<li key={i}>{task}</li>))}
<button onClick={() => context.actions.addTask("I am the task " + context.store.todos.length)}> + add </button>
</div>
}
```

Very often we will use the `useContext` hook that you see above
Very often we will use the `useContext` hook that you see above

```javascript
const context = useContext(AppContext);
return <div>
{context.store.todos.map((task, i) => (<li key={i}>{task}</li>))}
<button onClick={() => context.actions.addTask("I am the task " + context.store.todos.length)}> + add </button>
{context.store.todos.map((task, i) => (<li key={i}>{task}</li>))}
<button onClick={() => context.actions.addTask("I am the task " + context.store.todos.length)}> + add </button>
</div>
```

Expand All @@ -151,14 +152,13 @@ In its destructured variant. Pay attention to how that also simplifies the way w
```javascript
const {store, actions} = useContext(AppContext);
return <div>
{store.todos.map((task, i) => (<li>{task}</li>))}
<button onClick={() => actions.addTask("I am the task " + store.todos.length)}> + add </button>
{store.todos.map((task, i) => (<li>{task}</li>))}
<button onClick={() => actions.addTask("I am the task " + store.todos.length)}> + add </button>
</div>
```

## Test the code live

<iframe src="https://codesandbox.io/embed/w75wq6v01k?fontsize=14&hidenavigation=1&theme=dark" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>

<div align="right"><small><a href="https://codesandbox.io/s/w75wq6v01k?from-embed">Click here to open demo in a new window</a></small></div>
<iframe src="https://replit.com/@4GeeksAcademy/Demo-Context-API?embed=true&run=true#src/index.jsx" style="width:100%; height:500px; border:0; border-radius: 4px;" ></iframe>

<div align="right"><small><a href="https://replit.com/@4GeeksAcademy/Demo-Context-API?embed=true&run=true#src/index.jsx">Click here to open demo in a new window</a></small></div>
Empty file.
1 change: 1 addition & 0 deletions src/content/lesson/react-design-patterns.es.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# https://codesandbox.io/p/sandbox/higher-order-component-card-vv2grj?file=%2Fsrc%2FPlanetCard.js
44 changes: 38 additions & 6 deletions src/content/lesson/what-is-an-array-define-array.es.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,23 @@ Actualiza el array actual, devolviendo los elementos que se desean obtener. Debe

![qué es un array](https://github.com/breatheco-de/content/blob/master/src/assets/images/7e098348-df50-442b-801e-ac9d098fbc09.png?raw=true)

<iframe src="https://repl.it/F9V5/0?lite=true" frameborder="0" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="400px" scrolling="no" allowtransparency="true" allowfullscreen="true"></iframe>

<div align="right"><small><a href="https://repl.it/@4GeeksAcademy/Slice-vs-Splice">Clic para abrir demo en una ventana nueva</a></small></div>
```javascript runable=true
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

////////////////////////////
// Slice
let halfArr = numbers.slice(0, 5)
console.log({ halfArr })
// Ouputs: { halfArr: [ 1, 2, 3, 4, 5 ] }

////////////////////////////
// Splice
let middleItems = numbers.splice(4, 2)
console.log({ middleItems })
// Ouputs: { middleItems: [ 5, 6 ] }
console.log({ numbers, arr })
// Ouputs: { numbers: [ 1, 2, 3, 4, 7, 8, 9, 10 ] }
```

> ☝️ Splice puede aceptar tantos parámetros opcionales como se quiera y estos sustituirán la parte del array que ha sido eliminada. De esta forma el primer parámetro indica el índice desde el cual empieza a borrar, el segundo parámetro cuantos elementos borrarás y del tercero en adelante los elementos que se insertan a partir de la posición que se indica en el primer parámetro.

Expand Down Expand Up @@ -246,6 +260,24 @@ let autos = [
console.log(autos); // --> [ {tipo: 'Saab', año: 2001}, {tipo: 'BMW', año: 2010}, {tipo: 'Volvo', año: 2016} ]
```

<iframe src="https://repl.it/F9YZ/1?lite=true" frameborder="0" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="400px" scrolling="no" allowtransparency="true" allowfullscreen="true"></iframe>

<div align="right"><small><a href="https://repl.it/@4GeeksAcademy/Sorting-Arrays">Clic para abrir demo en una ventana nueva</a></small></div>
```javascript runable=true
// Sorting strings
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
console.log(fruits); // --> ['Apple', 'Banana', 'Mango', 'Orange']
fruits.reverse();
console.log(fruits); // --> ['Orange', 'Mango', 'Banana', 'Apple']

// Sorting numbers
let points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b) { return a - b });
console.log(points); // --> [1, 5, 10, 25, 40, 100]

// Sorting objects
let cars = [
{ type: "Volvo", year: 2016 },
{ type: "Saab", year: 2001 },
{ type: "BMW", year: 2010 }];
cars.sort(function(a, b) { return a.year - b.year });
console.log(cars); // --> [ {type: 'Saab', year: 2001}, {type: 'BMW', year: 2010}, {type: 'Volvo', year: 2016} ]
```
43 changes: 39 additions & 4 deletions src/content/lesson/what-is-an-array-define-array.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,9 +173,24 @@ Will update the current array, returning the items you want to retrieve. You wil

![what is an array define array](https://github.com/breatheco-de/content/blob/master/src/assets/images/7e098348-df50-442b-801e-ac9d098fbc09.png?raw=true)

<iframe src="https://repl.it/F9V5/0?lite=true" frameborder="0" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="400px" scrolling="no" allowtransparency="true" allowfullscreen="true"></iframe>
```javascript runable=true
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

////////////////////////////
// Slice
let halfArr = numbers.slice(0, 5)
console.log({ halfArr })
// Ouputs: { halfArr: [ 1, 2, 3, 4, 5 ] }

////////////////////////////
// Splice
let middleItems = numbers.splice(4, 2)
console.log({ middleItems })
// Ouputs: { middleItems: [ 5, 6 ] }
console.log({ numbers, arr })
// Ouputs: { numbers: [ 1, 2, 3, 4, 7, 8, 9, 10 ] }
```

<div align="right"><small><a href="https://repl.it/@4GeeksAcademy/Slice-vs-Splice">Click to open demo in a new window</a></small></div>


> ☝ Splice can accept as many optional parameters as wanted and those will substitute the part of the array that has been deleted. The first parameter is the index where the deletion starts, the second is how many elements will be deleted, and from the third onward, the elements inserted after the position set by the first parameter.
Expand Down Expand Up @@ -244,6 +259,26 @@ let cars = [
console.log(cars); // --> [ {type: 'Saab', year: 2001}, {type: 'BMW', year: 2010}, {type: 'Volvo', year: 2016} ]
```

<iframe src="https://repl.it/F9YZ/1?lite=true" frameborder="0" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals" width="100%" height="400px" scrolling="no" allowtransparency="true" allowfullscreen="true"></iframe>
Here's a runing example of all the above

```javascript runable=true
// Sorting strings
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
console.log(fruits); // --> ['Apple', 'Banana', 'Mango', 'Orange']
fruits.reverse();
console.log(fruits); // --> ['Orange', 'Mango', 'Banana', 'Apple']

// Sorting numbers
let points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b) { return a - b });
console.log(points); // --> [1, 5, 10, 25, 40, 100]

<div align="right"><small><a href="https://repl.it/@4GeeksAcademy/Sorting-Arrays">Click to open demo in a new window</a></small></div>
// Sorting objects
let cars = [
{ type: "Volvo", year: 2016 },
{ type: "Saab", year: 2001 },
{ type: "BMW", year: 2010 }];
cars.sort(function(a, b) { return a.year - b.year });
console.log(cars); // --> [ {type: 'Saab', year: 2001}, {type: 'BMW', year: 2010}, {type: 'Volvo', year: 2016} ]
```
Loading
Loading