Criando uma Lista de Contato (Parte 3 – Navigation)

Criando uma Lista de Contato (Parte 3 – Navigation)

Nesta aula iremos criar uma lista de contato utilizando os dados oriundos de um API adicionando o Navigation para um Header novo e adicionar um evento de clique na lista navegar até uma tela de detalhe.

Para criar um projeto novo veja as aulas anteriores.

Abra o projeto da aula anterior no Visual Code.

Crie na pasta src uma pasta chamada ‘pages’.

Depois adicione as dependências abaixo.

yarn add react-navigation
yarn add react-native-gesture-handler

App.js

Vamos criar um Header pelo navigation utilizando o createAppContainer e createStackNavigator.

</pre>
<div>
<div>import * as React from 'react';</div>
<div>import { View, Text } from 'react-native';</div>
<div>import { NavigationContainer } from '@react-navigation/native';</div>
<div>import { createStackNavigator } from '@react-navigation/stack';</div>
<div>import PeoplePage from './src/pages/PeoplePage'</div>
<div>import PeopleDetails from './src/pages/PeopleDetails';</div>
<div>//import PeoplePageDetails from './src/pages/PeoplePageDetails';</div>
<div>&nbsp;</div>
<div>function HomeScreen() {</div>
<div>return (</div>
<div>&lt;View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}&gt;</div>
<div>&lt;Text&gt;Home Screen&lt;/Text&gt;</div>
<div>&lt;/View&gt;</div>
<div>);</div>
<div>}</div>
<div>const Stack = createStackNavigator();</div>
<div>function App() {</div>
<div>return (</div>
<div>&lt;NavigationContainer&gt;</div>
<div>&lt;Stack.Navigator initialRouteName="People"&gt;</div>
<div>&lt;Stack.Screen name="People" component={PeoplePage} /&gt;</div>
<div>&lt;Stack.Screen name="PeopleDetails" component={PeopleDetails} /&gt;</div>
<div>&lt;/Stack.Navigator&gt;</div>
<div>&lt;/NavigationContainer&gt;</div>
<div>);</div>
<div>}</div>
<div>export default App;</div>
</div>
<pre>

PeoplePage.js

A página principal do projeto passará a ser PeoplePage que deverá ser criada na pasta recém criada pages.

import React from 'react';
import { View } from 'react-native';
import Header from '../component/Header';
import axios from 'axios';
import PeoppleList from '../component/PeopleList'
export default class PeoplePage extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      peoples: []
    }
  }

  componentDidMount(){
    axios
    .get('https://randomuser.me/api/?nat=br&amp;amp;results=10')
    .then(response =&amp;gt; {
      const {results} = response.data
      this.setState({
        peoples: results
      })
    })
  }

  render(){
    return (
        &amp;lt;View&amp;gt;
            &amp;lt;PeoppleList
                peoples={this.state.peoples}
                onPressItem={() =&amp;gt; {
                    this.props.navigation.navigate('PeopleDetails')
                    }}/&amp;gt;
        &amp;lt;/View&amp;gt;
    );
  }

}

PeopleList.js

A página PeopleList foi alterada somente pra receber o evento de clique ‘onPressItem’ que será passado para a PeopleListItem.

import React from 'react';
import {View, Text, StyleSheet} from 'react-native'
import PeopleListItem from './PeopleListItem'

const PeopleList = props =&amp;gt; {
    const {peoples, onPressItem} = props
    const items = peoples.map(people =&amp;gt; {
          return (
              &amp;lt;PeopleListItem
                    key={people.name.first}
                    people={people}
                    onPressItemDetails={onPressItem}/&amp;gt;
          )
        }
      )
    return (
        &amp;lt;View style={style.container}&amp;gt;
            {items}
        &amp;lt;/View&amp;gt;
    )
}

const style = StyleSheet.create({
    container: {
        backgroundColor: '#e2f977'
    },
}
)

export default PeopleList

PeopleListItem.js

O componente PeopleListItem foi alketrado para tratar o evento de clique com TouchableOpacity executando o evento recebido por props ‘onPressItemDetails’.

import React from 'react';
import { StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native';
import {toUpperFirst} from '../util'

const PeopleListItem = props =&amp;gt; {
    const {people, onPressItemDetails} = props
    const {title, first, last} = people.name
    return (
        &amp;lt;TouchableOpacity onPress={() =&amp;gt; {
                onPressItemDetails()
            }}&amp;gt;
            &amp;lt;View style={style.line}&amp;gt;
                &amp;lt;Image style={style.avatar} source={{uri: people.picture.thumbnail}}/&amp;gt;
                &amp;lt;Text style={style.linetext} key={first}&amp;gt;
                    {`${
                        toUpperFirst(title)
                    } ${
                        toUpperFirst(first)
                    } ${
                        toUpperFirst(last)
                    }`}
                &amp;lt;/Text&amp;gt;
            &amp;lt;/View&amp;gt;
            &amp;lt;/TouchableOpacity&amp;gt;
    )
}

const style = StyleSheet.create({
    line: {
        height: 60,
        borderBottomWidth: 1,
        borderBottomColor: '#bbb',
        alignItems: 'center',
        flexDirection: 'row'
    },
    linetext:{
        fontSize:20,
        paddingLeft: 20,
        flex: 7
    },
    avatar:{
        aspectRatio: 1,
        flex: 1,
        marginLeft: 10,
        borderRadius: 50
    }
}
)

export default PeopleListItem

PeoplePageDetails.js

A página de detalhes será trabalhada futuramente em outros artigos.

import React from 'react';
import { View, Text } from 'react-native';
export default class PeoplePageDetails extends React.Component{

  render(){
    return (
        &amp;lt;View&amp;gt;
            &amp;lt;Text&amp;gt;People Details Here!&amp;lt;/Text&amp;gt;
        &amp;lt;/View&amp;gt;
    )
  }
}

Deixe uma resposta

Specify Google Client ID and Secret in Super Socializer > Social Login section in admin panel for Google Login to work

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *