|
| 1 | +# 09 Sidebar |
| 2 | + |
| 3 | +En este ejemplo vamos a añadir una barra lateral a nuestra aplicación, empezaremos con una implementación específica, y luego la haremos genérica. |
| 4 | + |
| 5 | +# Pasos a seguir |
| 6 | + |
| 7 | +- Tomaremos como punto de partida el ejemplo _08 ColorPickerRefactor_, copiamos el contenido de ese archivo y ejecutamos _npm install_. |
| 8 | + |
| 9 | +```bash |
| 10 | +npm install |
| 11 | +``` |
| 12 | + |
| 13 | +- Cree un archivo llamado _src/sidebar.css_ y añada los siguientes estilos (http://www.w3schools.com/howto/howto_js_sidenav.asp): |
| 14 | + |
| 15 | +_./src/components/sidebar.css_ |
| 16 | + |
| 17 | +```css |
| 18 | +/* The side navigation menu */ |
| 19 | +.sidenav { |
| 20 | + height: 100%; /* 100% Full-height */ |
| 21 | + width: 0; /* 0 width - change this with JavaScript */ |
| 22 | + position: fixed; /* Stay in place */ |
| 23 | + z-index: 1; /* Stay on top */ |
| 24 | + top: 0; |
| 25 | + left: 0; |
| 26 | + background-color: #808080; /* Gray*/ |
| 27 | + overflow-x: hidden; /* Disable horizontal scroll */ |
| 28 | + padding-top: 60px; /* Place content 60px from the top */ |
| 29 | + transition: 0.5s; /* 0.5 second transition effect to slide in the sidenav */ |
| 30 | +} |
| 31 | + |
| 32 | +/* Position and style the close button (top right corner) */ |
| 33 | +.sidenav .closebtn { |
| 34 | + position: absolute; |
| 35 | + top: 0; |
| 36 | + right: 25px; |
| 37 | + font-size: 36px; |
| 38 | + margin-left: 50px; |
| 39 | +} |
| 40 | + |
| 41 | +/* Style page content - use this if you want to push the page content to the right when you open the side navigation */ |
| 42 | +#main { |
| 43 | + transition: margin-left 0.5s; |
| 44 | + padding: 20px; |
| 45 | +} |
| 46 | + |
| 47 | +/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */ |
| 48 | +@media screen and (max-height: 450px) { |
| 49 | + .sidenav { |
| 50 | + padding-top: 15px; |
| 51 | + } |
| 52 | + .sidenav a { |
| 53 | + font-size: 18px; |
| 54 | + } |
| 55 | +} |
| 56 | +``` |
| 57 | + |
| 58 | +- Vamos a usar módulos CSS, así que vamos a configurarlo. |
| 59 | + |
| 60 | +_./webpack.config.js_ |
| 61 | + |
| 62 | +```diff |
| 63 | + module.exports = { |
| 64 | + context: path.join(basePath, "src"), |
| 65 | + resolve: { |
| 66 | +- extensions: ['.js', '.ts', '.tsx'] |
| 67 | ++ extensions: ['.js', '.ts', '.tsx', '.css'] |
| 68 | + }, |
| 69 | +``` |
| 70 | + |
| 71 | +- Sólo usaremos módulos CSS para hojas de estilo personalizadas. No usaremos Módulos CSS para otros archivos CSS, como Bootstrap (carpeta node_modules). |
| 72 | + |
| 73 | +_./webpack.config.js_ |
| 74 | + |
| 75 | +```diff |
| 76 | + { |
| 77 | + test: /\.css$/, |
| 78 | ++ include: /node_modules/, |
| 79 | + use: [MiniCssExtractPlugin.loader, "css-loader"] |
| 80 | + }, |
| 81 | ++ // Use CSS modules for custom stylesheets |
| 82 | ++ { |
| 83 | ++ test: /\.css$/, |
| 84 | ++ exclude: /node_modules/, |
| 85 | ++ use: [ |
| 86 | ++ MiniCssExtractPlugin.loader, |
| 87 | ++ { |
| 88 | ++ loader: 'css-loader', |
| 89 | ++ options: { |
| 90 | ++ modules: true, |
| 91 | ++ localIdentName: '[name]__[local]___[hash:base64:5]', |
| 92 | ++ camelCase: true, |
| 93 | ++ }, |
| 94 | ++ }, |
| 95 | ++ ] |
| 96 | ++ }, |
| 97 | ++ // Do not use CSS modules in node_modules folder |
| 98 | + |
| 99 | +``` |
| 100 | + |
| 101 | +- Vamos a crear el componente de la barra lateral, _src/sidebar.tsx_. Crearemos sólo |
| 102 | + un rectángulo e interactuaremos con la animación. |
| 103 | + |
| 104 | +Necesitamos instalar los tipos para _node_, ya que usaremos _require_ a la hora de importar desde el _css_. |
| 105 | + |
| 106 | +```bash |
| 107 | +npm install @types/node --save-dev |
| 108 | +``` |
| 109 | + |
| 110 | +_./src/components/sidebar.tsx_ |
| 111 | + |
| 112 | +```jsx |
| 113 | +import * as React from "react"; |
| 114 | + |
| 115 | +const classNames = require("./sidebar.css"); |
| 116 | + |
| 117 | +export const SidebarComponent = () => ( |
| 118 | + <div id="mySidenav" className={classNames.sidenav}> |
| 119 | + <span>Basic side bar, first steps</span> |
| 120 | + </div> |
| 121 | +); |
| 122 | +``` |
| 123 | + |
| 124 | +- Añadimos este componente a nuestro barrel _index_ |
| 125 | + |
| 126 | +_./src/components/index.ts_ |
| 127 | + |
| 128 | +```diff |
| 129 | +export * from "./hello"; |
| 130 | +export * from "./nameEdit"; |
| 131 | +export * from "./colorBrowser"; |
| 132 | +export * from "./colorPicker"; |
| 133 | ++ export * from "./sidebar"; |
| 134 | +``` |
| 135 | + |
| 136 | +- Vamos a añadir un _id_ al elemento _body_ de la página _src/index.html_ |
| 137 | + |
| 138 | +_./src/index.html_ |
| 139 | + |
| 140 | +```diff |
| 141 | +- <body> |
| 142 | ++ <body id="main"> |
| 143 | +``` |
| 144 | + |
| 145 | +- Colocamos el componente añadiéndolo en `app.tsx`: |
| 146 | + |
| 147 | +_./src/app.tsx_ |
| 148 | + |
| 149 | +```diff |
| 150 | +import * as React from "react"; |
| 151 | +- import { HelloComponent, NameEditComponent, ColorBrowser, ColorPicker } from "./components"; |
| 152 | ++ import { HelloComponent, NameEditComponent, ColorBrowser, ColorPicker, SidebarComponent } from "./components"; |
| 153 | +import { Color } from "./model/color"; |
| 154 | +``` |
| 155 | + |
| 156 | +_./src/app.tsx_ |
| 157 | + |
| 158 | +```diff |
| 159 | + return ( |
| 160 | + <> |
| 161 | ++ <SidebarComponent /> |
| 162 | + <ColorBrowser color={color} /> |
| 163 | +``` |
| 164 | + |
| 165 | +- Comencemos con la parte interesante de esta implementación, agreguemos una opción para mostrar/ocultar la barra lateral _sidebar.tsx_. |
| 166 | + |
| 167 | +_./src/components/sidebar.tsx_ |
| 168 | + |
| 169 | +```diff |
| 170 | +import * as React from 'react'; |
| 171 | + |
| 172 | +const classNames = require('./sidebar.css'); |
| 173 | + |
| 174 | ++ interface Props { |
| 175 | ++ isVisible: boolean; |
| 176 | ++ } |
| 177 | + |
| 178 | +- export const SidebarComponent = () => |
| 179 | ++ export const SidebarComponent = (props: Props) => |
| 180 | + <div id="mySidenav" className={classNames.sidenav}> |
| 181 | + <span>Basic sidebar, first steps</span> |
| 182 | + </div> |
| 183 | +``` |
| 184 | + |
| 185 | +- Ahora vamos a añadir algo de lógica para mostrar / ocultar la barra lateral en caso de que se actualice dicha opción. |
| 186 | + |
| 187 | + |
| 188 | +_./src/sidebar.tsx_ |
| 189 | + |
| 190 | +```diff |
| 191 | +import * as React from 'react'; |
| 192 | + |
| 193 | +const classNames = require('./sidebar.css'); |
| 194 | + |
| 195 | +interface Props { |
| 196 | + isVisible: boolean; |
| 197 | +}; |
| 198 | + |
| 199 | ++ const divStyle = (props: Props): React.CSSProperties => ({ |
| 200 | ++ width: (props.isVisible) ? '23rem' : '0rem' |
| 201 | ++ }); |
| 202 | + |
| 203 | +export const SidebarComponent = (props: Props) => |
| 204 | +- <div id="mySidenav" className={classNames.sidenav}> |
| 205 | ++ <div id="mySidenav" className={classNames.sidenav} |
| 206 | ++ style={divStyle(props)} |
| 207 | ++ > |
| 208 | + <span>Basic sidebar, first steps</span> |
| 209 | + </div> |
| 210 | +``` |
| 211 | + |
| 212 | +- Hagamos una prueba rápida para mostrar siempre la barra lateral: |
| 213 | + |
| 214 | +_./src/app.tsx_ |
| 215 | + |
| 216 | +```diff |
| 217 | + return ( |
| 218 | + <> |
| 219 | +- <SidebarComponent /> |
| 220 | ++ <SidebarComponent isVisible={true}/> |
| 221 | + <ColorBrowser color={color} /> |
| 222 | +``` |
| 223 | + |
| 224 | +- Si arrancamos el proyecto veremos la barra lateral que hemos creado (un rectángulo gris). |
| 225 | + |
| 226 | + |
| 227 | +```bash |
| 228 | +npm start |
| 229 | +``` |
| 230 | +_¿Qué pasa si no puedo ver la barra lateral?_ Compruebe que _webpack.config.js_ y sus estilos se han aplicado, es posible que tenga que iniciar de nuevo _webpack-dev-sever_ (relanzar _npm start_), compruebe con dev tools que está cargando los estilos CSS. |
| 231 | + |
| 232 | +- Ahora a nivel de aplicación podemos recordar la opción de visibilidad, y añadir un botón para alternar la visualización de la barra lateral. |
| 233 | + |
| 234 | + |
| 235 | +_./src/app.tsx_ |
| 236 | + |
| 237 | +```diff |
| 238 | +export const App = () => { |
| 239 | + const [name, setName] = React.useState("defaultUserName"); |
| 240 | + const [editingName, setEditingName] = React.useState("defaultUserName"); |
| 241 | + const [color, setColor] = React.useState<Color>({ |
| 242 | + red: 20, |
| 243 | + green: 40, |
| 244 | + blue: 180 |
| 245 | + }); |
| 246 | ++ const[isVisible, setVisible] = React.useState(false); |
| 247 | +``` |
| 248 | + |
| 249 | +_./src/app.tsx_ |
| 250 | + |
| 251 | +```diff |
| 252 | + return ( |
| 253 | + <> |
| 254 | +- <SidebarComponent isVisible={true} /> |
| 255 | ++ <SidebarComponent isVisible={isVisible} /> |
| 256 | + <ColorBrowser color={color} /> |
| 257 | + <ColorPicker color={color} onColorUpdated={setColor} /> |
| 258 | + <HelloComponent userName={name} /> |
| 259 | + <NameEditComponent |
| 260 | + initialUserName={name} |
| 261 | + editingName={editingName} |
| 262 | + onNameUpdated={setUsernameState} |
| 263 | + onEditingNameUpdated={setEditingName} |
| 264 | + disabled={editingName === "" || editingName === name} |
| 265 | + /> |
| 266 | ++ <div style={{float: 'right'}}> |
| 267 | ++ <button |
| 268 | ++ onClick={() => setVisible(!isVisible)}> |
| 269 | ++ Toggle Sidebar |
| 270 | ++ </button> |
| 271 | ++ </div> |
| 272 | + </> |
| 273 | +``` |
| 274 | + |
| 275 | +- Iniciemos la aplicación para comprobar cómo se comporta: |
| 276 | + |
| 277 | +```bash |
| 278 | +npm start |
| 279 | +``` |
| 280 | + |
| 281 | +> Ejercicio: la llamada en línea a la función dentro de _onClick_ no se |
| 282 | +> considera una buena práctica (en cada render se recreará la función), |
| 283 | +> vamos a refactorizarla en dos pasos: |
| 284 | +
|
| 285 | +- Primero extraeremos esta lógica a una función, la llamaremos _toggleSidebarVisibility_. |
| 286 | + |
| 287 | +- Ahora envolvemos _visibility_ y _toggleSidebarVisibility_ en un _hook_ personalizado. |
| 288 | + |
| 289 | +* Hasta ahora todo va bien, pero ¿qué pasa si queremos que esta barra lateral sea un componente reutilizable? Podríamos simplemente mostrar el marco pero el contenido debe ser dinámico. |
| 290 | + |
| 291 | +* Comencemos por añadir algo de contenido al instanciar la barra lateral (_app.tsx_). |
| 292 | + |
| 293 | + |
| 294 | +_./src/app.tsx_ |
| 295 | + |
| 296 | +```diff |
| 297 | + <> |
| 298 | +- <SidebarComponent isVisible={isVisible} /> |
| 299 | ++ <SidebarComponent isVisible={isVisible}> |
| 300 | ++ <h1>Cool Scfi movies</h1> |
| 301 | ++ <ul> |
| 302 | ++ <li><a href="https://www.imdb.com/title/tt0816692/">Interstellar</a></li> |
| 303 | ++ <li><a href="https://www.imdb.com/title/tt0083658/">Blade Runner</a></li> |
| 304 | ++ <li><a href="https://www.imdb.com/title/tt0062622/">2001: a space odyssey</a></li> |
| 305 | ++ </ul> |
| 306 | ++ </SidebarComponent> |
| 307 | + <ColorBrowser color={color} /> |
| 308 | +``` |
| 309 | + |
| 310 | +> Tenemos un error, _children_ no está definido, vamos a arreglarlo en el |
| 311 | +> siguiente paso.... |
| 312 | +
|
| 313 | +- Ahora en _sidebar.tsx_ volcaremos este contenido usando {this.props.children} |
| 314 | + |
| 315 | +_./src/components/sidebar.tsx_ |
| 316 | + |
| 317 | +```diff |
| 318 | +- export const SidebarComponent = (props: Props) => ( |
| 319 | ++ export const SidebarComponent: React.StatelessComponent<Props> = (props) => ( |
| 320 | + |
| 321 | + <div id="mySidenav" className={classNames.sidenav} style={divStyle(props)}> |
| 322 | +- <span>Basic side bar, first steps</span> |
| 323 | ++ {props.children} |
| 324 | + </div> |
| 325 | +); |
| 326 | +``` |
| 327 | + |
| 328 | +- Probemos el ejemplo |
| 329 | + |
| 330 | +``` |
| 331 | +npm start |
| 332 | +``` |
| 333 | + |
| 334 | +# About Basefactor + Lemoncode |
| 335 | + |
| 336 | +We are an innovating team of Javascript experts, passionate about turning your ideas into robust products. |
| 337 | + |
| 338 | +[Basefactor, consultancy by Lemoncode](http://www.basefactor.com) provides consultancy and coaching services. |
| 339 | + |
| 340 | +[Lemoncode](http://lemoncode.net/services/en/#en-home) provides training services. |
| 341 | + |
| 342 | +For the LATAM/Spanish audience we are running an Online Front End Master degree, more info: http://lemoncode.net/master-frontend |
0 commit comments