DEV Community

Joao Carlos Sousa do Vale
Joao Carlos Sousa do Vale

Posted on

Learning React - Basic

REACT

Links

Concepts

  • SPA - Single Page Applications
  • JSX - html inside JS
  • fragment - tag empty

First project

npx create-react-app <app-name>
Enter fullscreen mode Exit fullscreen mode
  • inside the project
npm start
Enter fullscreen mode Exit fullscreen mode

Properties

  • sintaxe to inject
  <App message="Ola" user="Bob"/>
Enter fullscreen mode Exit fullscreen mode
  • usage
function App(props) {
  return (
    <>
      <h1>{props.message} {props.user}</h1>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

States

  • hook useState
  • returns two elements: [state, setState]
import React, { useState } from 'react';

function App(props) {
  const[user, setUser] = useState('BOB');
  return (
    <>
      <h1>Hello {user}</h1>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Controlled Components

  • Uses the state of React Component as source of truth.
const [user, setUser] = useState("");

...

<input className='usuarioInput' placeholder='Usuario' value={user} onChange={e => setUser(e.target.value)}/>
Enter fullscreen mode Exit fullscreen mode
  • full example
import './App.css';
import React, { useState } from 'react';
import axios from 'axios';

function App(props) {

  const [user, setUser] = useState("");

  function handlePesquisa() {
    axios.get(`https://api.github.com/users/${user}/repos`)
    .then(response => 
      {
        console.log(response.data)
      });
    }

  return (
    <>
      <input className='usuarioInput' placeholder='Usuario' value={user} onChange={e => setUser(e.target.value)}/>
      <button type='button' onClick={handlePesquisa}>Pesquisar</button>
    </>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

ROUTER

import React from "react";
import {Routes, BrowserRouter, Route,  } from "react-router-dom";
import Home from "./Home";

import Repositories from "./Repositories";

export default function Routers() {
  return (
          <BrowserRouter>
            <Routes>
              <Route path="/" exact element={<Home/>} />
              <Route path="/repositories" element={<Repositories/>} />
            </Routes>
          </BrowserRouter>
  );
}
Enter fullscreen mode Exit fullscreen mode
  • injecting, the Home component is the default
import React from 'react';
import Routers from './routes';

function App() {
  return (
    <Routers/>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode
  • using navigate
import { useNavigate } from 'react-router-dom';

...

export default function Home(props) {

  const navigate = useNavigate();
  const [user, setUser] = useState("");

  function handlePesquisa() {
    axios.get(`https://api.github.com/users/${user}/repos`)
            .then(response => {
              const repositories = response.data;
              const repositoriesName = [];
              repositories.map(repository => repositoriesName.push(repository.name));
              localStorage.setItem('repositoriesName', JSON.stringify(repositoriesName));
              console.log(repositoriesName);
              navigate('/repositories');
            });
  }
...
Enter fullscreen mode Exit fullscreen mode
  • using Link
import { Link } from "react-router-dom";
...
<Link to='/'>Voltar</Link>
Enter fullscreen mode Exit fullscreen mode

Using local storage

  function handlePesquisa() {
  axios.get(`https://api.github.com/users/${user}/repos`)
          .then(response => {
            const repositories = response.data;
            const repositoriesName = [];
            repositories.map(repository => repositoriesName.push(repository.name));
            localStorage.setItem('repositoriesName', JSON.stringify(repositoriesName));
            console.log(repositoriesName);
          });
}
Enter fullscreen mode Exit fullscreen mode

Styled-Components

  • to style elements, like:
import styled from 'styled-components';


export const Container = styled.div`
    width: 100vw;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
`;


export const Input = styled.input`
    border: 1px solid #ddd;
    height: 1.5rem;
    padding: 0 .5rem;
    border-radius: .25rem 0 0 .25rem;

    &:focus,
    &:active {
        outline: none;
        box-shadow: none;
    }
`;

export const Button = styled.button`
    height: 1.5rem;
    border: 1px solid #000;
    background: #000;
    color: #fff;
    border-radius: 0 .25rem .25rem 0;
`;
Enter fullscreen mode Exit fullscreen mode
  • usage example
import * as S from './styled';

  return (
    <S.Container>
      <S.Input className='usuarioInput' placeholder='Usuario' value={user} onChange={e => setUser(e.target.value)}></S.Input>
      <S.Button type='button' onClick={handlePesquisa}>Pesquisar</S.Button>
    </S.Container>
  );
Enter fullscreen mode Exit fullscreen mode
  • styling in react components
import { Link } from "react-router-dom";

export const LinkHome = styled(Link)`
    display: block;
    width: 4rem;
    text-align: center;
    margin: 2rem auto;
    background-color: #000;
    padding: .5rem 0;
    color: #fff;
    text-decoration: none;
`;
Enter fullscreen mode Exit fullscreen mode

Conditional Rendering

  • verify the error variable below
import '../../App.css';
import React, { useState } from 'react';
import axios from 'axios';
import * as S from './styled';
import { useNavigate } from 'react-router-dom';

export default function Home(props) {

  const navigate = useNavigate();
  const [user, setUser] = useState("");
  const [error, setError] = useState(false);

  function handlePesquisa() {
    axios.get(`https://api.github.com/users/${user}/repos`)
    .then(response => {
        const repositories = response.data;
        const repositoriesName = [];
        repositories.map(repository => repositoriesName.push(repository.name));
        localStorage.setItem('repositoriesName', JSON.stringify(repositoriesName));
        console.log(repositoriesName);
        setError(false);
        navigate('/repositories');
      })
    .catch(error => {
        setError(true)
      });
    }

  return (
    <S.HomeContainer>
      <S.Container>
        <S.Input className='usuarioInput' placeholder='Usuario' value={user} onChange={e => setUser(e.target.value)}></S.Input>
        <S.Button type='button' onClick={handlePesquisa}>Pesquisar</S.Button>
      </S.Container>
      {
        error ? <S.ErrorMsg>Ocorreu um erro. Tente novamente.</S.ErrorMsg> : ' '
      }

    </S.HomeContainer>
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
suraj__ profile image
Suraj

📚