One place for hosting & domains

      Navigation

      12 Navigation Menu Design Tips for a Better User Experience


      While creating attractive and valuable web pages is important, your efforts can be wasted if they are unorganized. This could make it difficult for users to view and interact with your content, leading to bounces (page exits) and potentially lower search engine rankings.

      Fortunately, you can design the perfect navigation menu to help users quickly find the pages they’re looking for. With many styles and formats to choose from, you’re able to create menus that impress visitors and deliver an excellent User Experience (UX).

      In this post, we’ll introduce you to navigation menus. Then, we’ll explore twelve useful tips for designing your menus as well as share some examples to inspire you.

      Ready? Let’s get started!

      An Introduction to Navigation Menus

      Navigation menus display an organized list of all your web pages from one dedicated area. Typically, they appear across headers or sidebars, so that they’re clearly visible and accessible for your website visitors.

      Menus enable users to navigate around your site more easily, but they also help them to make sense of your content. For instance, by viewing your menu, users can better understand the relationships between your web pages:

      mega menu dropdown example

      When setting up your navigation menu, you might consider featuring submenus or local navigation menus within your overarching main menu. Then, you can add lower levels of categories to your navigation if you have lots of content on your site.

      12 Tips for Designing the Perfect Navigation Menu

      Now that you know how helpful navigation menus can be, let’s take a look at twelve useful tips for designing one.

      1. Prioritize Accessibility

      A well–designed website is one where users don’t have to work hard to find what they’re looking for. Meaning, when a visitor lands on your page, they should be able to quickly locate your menu and understand how to use it:

      stylized dropdown navigation menu

      Although you can be creative, it’s important to prioritize designing an accessible website. Therefore, try to avoid vague or complex labels that might confuse readers. Instead, opt for clear fonts, high-contrast colors, and direct language.

       

      2. Optimize the User Experience (UX) 

      Providing a quality UX can boost your conversions and reduce bounce rate. To optimize your UX, aim to keep your menu simple so users don’t have to get to grips with complex systems. There’s a lot to be said for neat, clean designs that allow visitors to breeze through your website.

      It’s a general rule of thumb that in three clicks or less, people should be able to land where they want to be on your site. That’s why websites with lots of content areas often choose mega menus:

      mega menu navigation menu design

      These mega menus are frequently used by large e-commerce stores since they make all pages accessible from one space.

      Another factor that can impact your UX is your hosting provider. DreamHost provides quality shared hosting that can set you up with customizable themes and must-have plugins for all types of websites. We also offer user-friendly interfaces plus regular updates and around-the-clock support.

      3. Stick with Straightforward Designs

      You might be tempted to fill your menus with lots of effects to impress your visitors. However, consider saving the flashy features for your overall web design. Still, you might like to include images if it assists with your navigation goals:

      navigation menu active and hover state design example

      Another option is to utilize relevant, helpful icons such as directional arrows to guide users through your sections.

      4. Appeal to Your Audience     

      You can’t design the perfect navigation menu without considering your unique target audience. With this in mind, you can choose color schemes, typefaces, and call-to-actions (CTAs) that are more likely to appeal to your market. This can make your links appear more clickable.

      For example, a hard news website is unlikely to use the same font and messaging as a quirky baking blog:

      split navigation menu design with logo at center

      When choosing headings or CTAs to feature in your menu, you’ll want to inspire users to act. Essentially, visitors need to be incentivized to read further or discover more of your content.

      5. Be Consistent

      It’s important that the format and design of your menu meets your visitors’ expectations. So, consider using the same styling options to highlight menu items. This way, users know when a link will take them to a new page or expand into a dropdown menu.

      For example, Benefit’s website uses directional arrows beside links that expand into dropdown menus:

      simple mega menu with call-to-action

      Additionally, it can be helpful to distinguish between primary and secondary headings. You might want to do this by making top-level menu items slightly larger, or applying a bold style to indicate more significance.

      6. Organize Appropriately 

      A navigation menu is an ideal way to organize your web pages. Plus, it enables users to view your content in a way that makes sense. For instance, blogs can organize posts by topics while an e-commerce website might group products by categories:

      multi-level dropdown menu design example

      Once you’ve identified the main categories of your content, you can build your navigation menu around this. It’s also useful to choose relevant headings that properly describe the page.

      7. Establish a Clear Hierarchy

      Implementing a hierarchy within your menu enables you to break content up into smaller chunks. This makes it more digestible for users. As such, try to group relevant information together.

      For some websites, it can be useful to organize information according to what is most popular or important to visitors. Then, you can make these headings stand out within your menu. Strive to achieve a balance between showing users pages of interest while also leading them towards pages that best serve your business goals.

      Get Content Delivered Straight to Your Inbox

      Subscribe to our blog and receive great content just like this delivered straight to your inbox.

      8. Consider the Mobile Experience

      A responsive menu will display attractively across different size screens such as smartphones and tablets. This is important since nearly 60% of total global traffic comes from mobile phones.

      Most websites tend to opt for hamburger menus for mobile devices:

      mobile nav menu design

      Failing to build a responsive website is arguably one of the biggest mistakes you can make when it comes to web design. Therefore, as you are creating your menu, consider which links are most important to include in your primary menu as this is what will be seen on smaller screens.

      9. Use Familiar Web Conventions

      Designing your menu with unfamiliar conventions might require users to learn new practices, which can be inconvenient and annoying, so you’ll want to avoid this. For instance, most users are accustomed to clicking on the website logo to return to the homepage.

      If your logo leads to a signup or product page, this may confuse your visitors. Another common convention is ‘visited’ links changing color. Including these well-known practices on your website enables users to intuitively navigate your pages.

      10. Optimize for Search Engines

      In order to drive more organic traffic to your website, you can optimize your navigation headings with popular keywords. Google Analytics and Google Keyword Planner are excellent tools that enable you to identify which words and phrases users are searching:

      getting keyword ideas in Google Keyword Planner

      Then, you can include these key terms within your menu. As a result, your website may just rank higher in search engines.

      11. Choose the Right Type of Menu

      There are many types of navigation menus to consider. Dropdown menus often display when you hover or click primary categories. Then, you’re presented with a list of secondary items.

      These menus look stylish and modern. Plus, they’re a great way to conserve space:

      simple dropdown navigation menu design

      You can go a step further and design a complete mega menu. These are best used for content-rich sites, since they can present all your pages without appearing too clunky:

      menu menu navigation design example

      Horizontal menus, which list major pages in a row format, are also quite common. Alternatively, a vertical menu, listed in a column at the side of the page, assists readers with scanning, since eyes naturally move down (not across):

      stylized sidebar navigation menu design

      Vertical menus tend to be a good match for websites with longer menu labels since they offer more space. However, they can also be eye-catching, which makes them a good choice for creative service sites.

      12. Add Breadcrumbs

      Breadcrumbs enable users to see where they are within your site’s structure. Plus, they make it easy for visitors to return to high-tier pages that led them to their current location:

      sidebar navigation menu design example

      Adding breadcrumbs to your menu avoids users needing to navigate all the way back to the beginning. Instead, they can easily jump back a step or two to find what they need.

      Excellent Examples of Navigation Menus 

      Now that you know how to design the perfect menu for your site, let’s take a look at some examples.

      Mostly Serious

      Mostly Serious features a clear hamburger icon to make room for a fun animation:

      off canvas menu design default state

      When you click on the icon, it opens a vertical sidebar menu with only the primary headings displayed:

      off canvas menu design expanded active state

      Once you start scrolling past the animation, you’ll see a sticky horizontal menu that’s neat and accessible, without distracting from the experience of reading the page:

      fixed nav bar example

      In this example, each type of menu is used appropriately. On top of that, when you hover over menu items, all navigational links are highlighted in bright blue and underlined for consistency.

      Bobbi Brown

      The Bobbi Brown website features a primary horizontal menu nestled beneath the heading. This makes it one of the first things you see when you land on the page.

      Each of the main menu items features its own dropdown menu that includes text links among high-quality images, which make the menu more engaging:

      simple mega menu with images

      Additionally, the menu is organized effectively, with the most important categories appearing first such as New and Bestsellers. Even within the dropdown menus, image links prioritize the most useful customer pages, while other areas of the site are stacked vertically at the side.

      This is Amber

      This is Amber features a quirky off-canvas flyout menu in the form of tabs that expand when clicked. Then, the selected page slides across, replacing the existing page you’re viewing:

      horizontal navigation menu design

      It’s an incredibly unique way of displaying menu items. Plus, it does a great job of building a brand identity. Visitors can also access the primary links through a horizontal header menu at the top of the page.

      Blackbird Cigar

      Blackbird Cigar uses a hamburger menu, which opens a vertical menu when clicked. This is styled like a dropdown menu although links open across instead of down:

      nested sidebar navigation menu design

      Moreover, the menu features a stylish design that conveys a clear hierarchy, enabling visitors to understand the relationship between pages. For example, when visitors hover over primary links, they turn transparent, while secondary links are distinguished from top-tier pages using contrasting colors.

      French but Nice

      French but Nice is a portfolio website that uses a captivating vertical sidebar menu that organizes projects chronologically:

      brutalist sidebar navigation design

      When a user hovers over one of the links, a preview of the page appears in a lightbox. This is particularly useful for a website of this kind, since visitors can view multiple projects without leaving the menu.

      Create the Perfect Navigation Menu

      A navigation menu is a necessary part of any website, so it’s important to make sure that yours is user-friendly and effective. Otherwise, your content can be difficult to find and hard to make sense of.

      However, when you follow a few (or all) of our top tips, you’ll be able to more easily design the perfect navigation menu. For instance, you might choose a hamburger menu so that your pages can be viewed on mobile devices. Or, you could utilize strong colors, fonts, and images to make your links more clickable.

      At DreamHost, we understand the importance of getting your content online quickly. That’s why we offer Shared Hosting with SSL certificates, a domain, and privacy protection to get you set up in no time. Choose a plan today to get started!

      Great Design, Powered by DreamHost

      We make sure your website is fast, secure and always up so your visitors trust you. Plans start at $1.99/mo.

      shared hosting



      Source link

      Cara Menggunakan Perutean dengan React Navigation di React Native


      Pengantar

      React Navigation adalah pustaka populer untuk perutean dan navigasi di aplikasi React Native.

      Pustaka ini membantu memecahkan masalah navigasi di antara beberapa layar dan berbagi data antar layar.

      Di akhir tutorial ini, Anda akan memiliki jaringan sosial dasar. Tutorial ini akan menampilkan sejumlah hubungan yang dimiliki pengguna dan menyediakan cara menghubungkan dengan teman lainnya. Anda akan menggunakan aplikasi sampel ini untuk mendalami cara navigasi layar aplikasi seluler menggunakan react-navigation.

      Prasyarat

      Untuk menyelesaikan tutorial ini, Anda membutuhkan:

      Catatan: Jika dahulu Anda menggunakan react-navigation, Anda mungkin akan menemukan banyak perbedaan. Anda dapat membaca dokumentasi untuk panduan tentang migrasi dari 3.x dan migrasi dari 4.x.

      Tutorial ini telah diverifikasi pada Node v14.7.0, npm v6.14.7, react v16.13.1, react-native v0.63.2, @react-navigation/native v5.7.3, dan @react-navigation/stack v5.9.0.

      Langkah 1 — Membuat Aplikasi React Native Baru

      Pertama, buat aplikasi React Native baru dengan memasukkan perintah berikut di terminal Anda:

      • npx react-native init MySocialNetwork --version 0.63.2

      Kemudian, masuk ke direktori baru:

      Lalu mulai aplikasi untuk iOS:

      Atau, untuk Android:

      Catatan: Jika mengalami masalah, Anda mungkin perlu membaca pemecahan masalah untuk React Native CLI.

      Ini akan membuat proyek kerangka untuk Anda. Penampilannya sangat tidak mirip jaringan sosial yang ada sekarang ini. Mari kita perbaiki.

      Buka App.js:

      Ganti isi App.js dengan kode berikut untuk menampilkan pesan sambutan:

      App.js

      import React from 'react';
      import { StyleSheet, Text, View } from 'react-native';
      
      class App extends React.Component {
        render() {
          return (
            <View style={styles.container}>
              <Text>Welcome to MySocialNetwork!</Text>
            </View>
          );
        }
      }
      
      const styles = StyleSheet.create({
        container: {
          flex: 1,
          backgroundColor: '#fff',
          alignItems: 'center',
          justifyContent: 'center',
        },
      });
      
      export default App;
      

      Simpan berkas tersebut. Sekarang, bila Anda menjalankan aplikasi, pesan Selamat datang di MySocialNetwork! akan muncul di simulator Anda.

      Di langkah selanjutnya, Anda akan menambahkan layar lainnya ke aplikasi.

      Langkah 2 — Membuat HomeScreen dan FriendsScreen

      Saat ini, Anda memiliki satu layar yang menampilkan pesan sambutan. Dalam langkah ini, Anda akan membuat dua layar untuk aplikasi: HomeScreen dan FriendsScreen.

      HomeScreen

      Aplikasi Anda akan membutuhkan HomeScreen. HomeScreen akan menampilkan jumlah teman yang sudah ada di jaringan Anda.

      Ambil kode dari App.js dan tambahkan ke berkas baru bernama HomeScreen.js:

      Buka HomeScreen.js:

      Modifikasi HomeScreen.js untuk menggunakan HomeScreen sebagai ganti App:

      HomeScreen.js

      import React from 'react';
      import { StyleSheet, Text, View } from 'react-native';
      
      class HomeScreen extends React.Component {
        render() {
          return (
            <View style={styles.container}>
              <Text>You have (undefined) friends.</Text>
            </View>
          );
        }
      }
      
      // ...
      
      export default HomeScreen;
      

      Kode ini akan menghasilkan pesan penampung You have (undefined) friends.. Nanti, Anda akan memberikan suatu nilai.

      FriendsScreen

      Aplikasi Anda juga akan membutuhkan FriendsScreen. Di FriendsScreen, Anda dapat menambahkan teman baru.

      Ambil kode dari App.js dan tambahkan ke berkas baru bernama FriendsScreen.js:

      • cp App.js FriendsScreen.js

      Buka FriendsScreen.js:

      Modifikasi FriendsScreen.js untuk menggunakan FriendsScreen sebagai ganti App:

      FriendsScreen.js

      import React from 'react';
      import { StyleSheet, Text, View } from 'react-native';
      
      class FriendsScreen extends React.Component {
        render() {
          return (
            <View style={styles.container}>
              <Text>Add friends here!</Text>
            </View>
          );
        }
      }
      
      // ...
      
      export default FriendsScreen;
      

      Kode ini akan menghasilkan pesan Add friends here!. .

      Saat ini, Anda memiliki HomeScreen dan FriendsScreen. Namun, tidak ada cara navigasi di antara layar-layar tersebut. Anda akan membangun fungsionalitas ini di langkah selanjutnya.

      Langkah 3 — Menggunakan StackNavigator dengan React Navigation

      Untuk navigasi di antara beberapa layar, Anda akan menggunakan StackNavigator. Cara kerja StackNavigator persis seperti call stack. Setiap layar yang Anda tuju akan didorong ke bagian atas tumpukan. Setiap kali menekan tombol kembali, layar-layar akan bermunculan di bagian atas tumpukan.

      Pertama, instal @react-navigation/native:

      • npm install @react-navigation/native@5.7.3

      Kemudian, instal @react-navigation/stack dan dependensi peer-nya:

      • npm install @react-navigation/stack@5.9.0 @react-native-community/masked-view@0.1.10 react-native-screens@2.10.1 react-native-safe-area-context@3.1.4 react-native-gesture-handler@1.7.0

      Catatan: Jika mengembangkan untuk iOS, Anda mungkin perlu masuk ke direktori ios dan menjalankan pod install.

      Selanjutnya, kembali ke App.js:

      Tambahkan NavigationContainer dan createStackNavigator ke App.js:

      App.js

      import 'react-native-gesture-handler';
      import React from 'react';
      import { StyleSheet } from 'react-native';
      import { NavigationContainer } from '@react-navigation/native';
      import { createStackNavigator } from '@react-navigation/stack';
      
      const Stack = createStackNavigator();
      

      Kemudian, ganti isi render:

      App.js

      // ...
      
      class App extends React.Component {
        render() {
          return (
            <NavigationContainer>
              <Stack.Navigator>
              </Stack.Navigator>
            </NavigationContainer>
          );
        }
      }
      
      // ...
      

      Disarangkan di dalam <Stack.Navigator>, tambahkan HomeScreen:

      App.js

      import 'react-native-gesture-handler';
      import React from 'react';
      import { StyleSheet } from 'react-native';
      import { NavigationContainer } from '@react-navigation/native';
      import { createStackNavigator } from '@react-navigation/stack';
      import HomeScreen from './HomeScreen';
      
      const Stack = createStackNavigator();
      
      class App extends React.Component {
        render() {
          return (
            <NavigationContainer>
              <Stack.Navigator>
                <Stack.Screen
                  name="Home"
                  component={HomeScreen}
                />
              </Stack.Navigator>
            </NavigationContainer>
          );
        }
      }
      
      // ...
      

      Kode ini membuat tumpukan sangat kecil untuk navigator Anda dengan satu layar saja: HomeScreen.

      Disarangkan di dalam <Stack.Navigator>, tambahkan FriendsScreen:

      App.js

      import 'react-native-gesture-handler';
      import React from 'react';
      import { StyleSheet } from 'react-native';
      import { NavigationContainer } from '@react-navigation/native';
      import { createStackNavigator } from '@react-navigation/stack';
      import HomeScreen from './HomeScreen';
      import FriendsScreen from './FriendsScreen';
      
      const Stack = createStackNavigator();
      
      class App extends React.Component {
        render() {
          return (
            <NavigationContainer>
              <Stack.Navigator>
                <Stack.Screen
                  name="Home"
                  component={HomeScreen}
                />
                <Stack.Screen
                  name="Friends"
                  component={FriendsScreen}
                />
              </Stack.Navigator>
            </NavigationContainer>
          );
        }
      }
      
      // ...
      

      Kode ini menambahkan FriendsScreen ke navigator.

      Catatan: Ini berbeda dengan cara menggunakan createStackNavigator di React Navigation versi sebelumnya.

      Sekarang, navigator mengetahui kedua layar Anda.

      Menambahkan Tombol ke HomeScreen dan FriendsScreen

      Terakhir, tambahkan tombol untuk membawa Anda di antara dua layar.

      Dalam HomeScreen.js, tambahkan kode berikut:

      HomeScreen.js

      import React from 'react';
      import { StyleSheet, Text, View, Button } from 'react-native';
      
      class HomeScreen extends React.Component {
        render() {
          return (
            <View style={styles.container}>
              <Text>You have (undefined) friends.</Text>
      
              <Button
                title="Add some friends"
                onPress={() =>
                  this.props.navigation.navigate('Friends')
                }
              />
            </View>
          );
        }
      }
      
      // ...
      

      Dalam FriendsScreen.js, tambahkan kode berikut:

      FriendsScreen.js

      import React from 'react';
      import { StyleSheet, Text, View, Button } from 'react-native';
      
      class FriendsScreen extends React.Component {
        render() {
          return (
            <View style={styles.container}>
              <Text>Add friends here!</Text>
      
              <Button
                title="Back to home"
                onPress={() =>
                  this.props.navigation.navigate('Home')
                }
              />
            </View>
          );
        }
      }
      
      // ...
      

      Mari kita bahas this.props.navigation. Selama layar Anda disertakan di StackNavigator, layar itu secara otomatis akan mewarisi banyak properti berguna dari objek navigation. Dalam hal ini, Anda menggunakan navigate untuk berpindah ke halaman yang berbeda.

      HomeScreen dan FriendsScreen

      Jika sekarang Anda membuka simulator, Anda dapat melakukan navigasi di antara HomeScreen dan FriendsScreen.

      Langkah 4 — Menggunakan Context untuk Menyalurkan Data ke Layar Lain

      Dalam langkah ini, Anda akan membuat larik kemungkinan teman — Alice, Bob, dan Sammy — dan larik kosong dari teman saat ini. Anda juga akan membuat fungsionalitas bagi pengguna untuk menambahkan kemungkinan teman ke teman-temannya saat ini.

      Buka App.js:

      Tambahkan possibleFriends dan currentFriends ke status komponen:

      App.js

      // ...
      
      class App extends React.Component {
        constructor(props) {
          super(props)
          this.state = {
            possibleFriends: [
              'Alice',
              'Bob',
              'Sammy',
            ],
            currentFriends: [],
          }
        }
      
        // ...
      }
      
      // ...
      

      Selanjutnya, tambahkan fungsi untuk memindahkan kemungkinan teman ke daftar teman saat ini:

      App.js

      // ...
      
      class App extends React.Component {
        constructor(props) {
          super(props)
          this.state = {
            possibleFriends: [
              'Alice',
              'Bob',
              'Sammy',
            ],
            currentFriends: [],
          }
        }
      
        addFriend = (index) => {
          const {
            currentFriends,
            possibleFriends,
          } = this.state
      
          // Pull friend out of possibleFriends
          const addedFriend = possibleFriends.splice(index, 1)
      
          // And put friend in currentFriends
          currentFriends.push(addedFriend)
      
          // Finally, update the app state
          this.setState({
            currentFriends,
            possibleFriends,
          })
        }
      
        // ...
      }
      
      // ...
      

      Saat ini, Anda telah selesai membangun fungsionalitas untuk menambahkan teman.

      Menambahkan FriendsContext ke App

      Sekarang Anda dapat menambahkan teman di App.js, tetapi Anda nanti perlu menambahkannya ke FriendsScreen.js, dan membuatnya ditampilkan di HomeScreen.js. Karena proyek ini dibuat dengan React, Anda dapat memasukkan fungsionalitas ini ke dalam layar yang memiliki konteks.

      Catatan: Di React Navigation versi sebelumnya, kita dapat menggunakan screenProps untuk berbagi data di antara layar. Dalam React Navigation versi saat ini, disarankan menggunakan React Context untuk berbagi data di antara layar.

      Untuk menghindari referensi melingkar, Anda nanti memerlukan berkas FriendsContext baru:

      Ekspor FriendsContext:

      FriendsContext

      import React from 'react';
      
      export const FriendsContext = React.createContext();
      

      Buka App.js:

      Tambahkan FriendsContext:

      App.js

      import 'react-native-gesture-handler';
      import React from 'react';
      import { StyleSheet } from 'react-native';
      import { NavigationContainer } from '@react-navigation/native';
      import { createStackNavigator } from '@react-navigation/stack';
      import { FriendsContext } from './FriendsContext';
      import Home from './Home';
      import Friends from './Friends';
      
      const Stack = createStackNavigator();
      
      class App extends React.Component {
        // ...
      
        render() {
          return (
            <FriendsContext.Provider>
              <NavigationContainer>
                <Stack.Navigator>
                  <Stack.Screen
                    name="Home"
                    component={Home}
                  />
                  <Stack.Screen
                    name="Friends"
                    component={Friends}
                  />
                </Stack.Navigator>
              </NavigationContainer>
            </FriendsContext.Provider>
          );
        }
      }
      
      // ...
      

      Kode ini membuat FriendsContext sebagai objek Context baru dan membungkus NavigationContainer dalam komponen Context.Provider sehingga anak-anak di pohon komponen dapat berlangganan perubahan konteks.

      Karena Anda tidak lagi menggunakan View atau Text, bisa saja menghapus impor itu dari react-native.

      Anda nanti perlu memberikan value agar data dapat diakses oleh konsumen:

      App.js

      // ...
      
      class App extends React.Component {
        // ...
      
        render() {
          return (
            <FriendsContext.Provider
              value={
                {
                  currentFriends: this.state.currentFriends,
                  possibleFriends: this.state.possibleFriends,
                  addFriend: this.addFriend
                }
              }
            >
              <NavigationContainer>
                <Stack.Navigator>
                  <Stack.Screen
                    name="Home"
                    component={Home}
                  />
                  <Stack.Screen
                    name="Friends"
                    component={Friends}
                  />
                </Stack.Navigator>
              </NavigationContainer>
            </FriendsContext.Provider>
          );
        }
      }
      
      // ...
      

      Ini akan memungkinkan HomeScreen dan FriendsScreen untuk merujuk perubahan konteks apa pun pada currentFriends dan possibleFriends.

      Sekarang Anda dapat mengerjakan perujukan konteks di layar.

      Menambahkan FriendsContext ke HomeScreen

      Dalam langkah ini, Anda akan menyiapkan aplikasi untuk menampilkan jumlah teman saat ini.

      Buka HomeScreen.js:

      Lalu tambahkan FriendsContext:

      HomeScreen.js

      import React from 'react';
      import { StyleSheet, Text, View, Button } from 'react-native';
      import { FriendsContext } from './FriendsContext';
      
      class HomeScreen extends React.Component {
        // ...
      }
      HomeScreen.contextType = FriendsContext;
      
      // ...
      

      Kode ini membuat Class.contextType. Kini Anda dapat mengakses konteks di layar.

      Misalnya, mari kita buat agar HomeScreen menampilkan jumlah currentFriends yang Anda miliki:

      HomeScreen.js

      import React from 'react';
      import { StyleSheet, Text, View, Button } from 'react-native';
      import { FriendsContext } from './FriendsContext';
      
      class Home extends React.Component {
        render() {
          return (
            <View style={styles.container}>
              <Text>You have { this.context.currentFriends.length } friends!</Text>
      
              <Button
                title="Add some friends"
                onPress={() =>
                  this.props.navigation.navigate('Friends')
                }
              />
            </View>
          );
        }
      }
      HomeScreen.contextType = FriendsContext;
      
      // ...
      

      Jika Anda membuka aplikasi lagi di simulator dan menampilkan HomeScreen, Anda akan melihat pesan: You have 0 friends!.

      Menambahkan FriendsContext ke FriendsScreen

      Dalam langkah ini, Anda akan menyiapkan aplikasi untuk menampilkan kemungkinan teman dan menyediakan tombol untuk menambahkannya ke teman saat ini.

      Selanjutnya, buka FriendsScreen.js:

      Lalu tambahkan FriendsContext:

      FriendsScreen.js

      import React from 'react';
      import { StyleSheet, Text, View, Button } from 'react-native';
      import { FriendsContext } from './FriendsContext';
      
      class FriendsScreen extends React.Component {
        // ...
      }
      FriendsScreen.contextType = FriendsContext;
      
      // ...
      

      Kode ini membuat Class.contextType.

      Sekarang, buat tombol untuk menambahkan teman di FriendsScreen.js:

      FriendsScreen.js

      import React from 'react';
      import { StyleSheet, Text, View, Button } from 'react-native';
      import { FriendsContext } from './FriendsContext';
      
      class Friends extends React.Component {
        render() {
          return (
            <View style={styles.container}>
              <Text>Add friends here!</Text>
      
              {
                this.context.possibleFriends.map((friend, index) => (
                  <Button
                    key={ friend }
                    title={ `Add ${ friend }` }
                    onPress={() =>
                      this.context.addFriend(index)
                    }
                  />
                ))
              }
      
              <Button
                title="Back to home"
                onPress={() =>
                  this.props.navigation.navigate('Home')
                }
              />
            </View>
          );
        }
      }
      FriendsScreen.contextType = FriendsContext;
      
      // ...
      

      Jika Anda membuka aplikasi lagi di simulator dan menampilkan FriendsScreen, Anda akan melihat daftar teman untuk ditambahkan.

      HomeScreen dengan 0 currentFriends dan FriendsScreen dengan 3 possibleFriends

      Jika Anda masuk ke FriendsScreen dan mengklik tombol untuk menambahkan teman, Anda akan melihat daftar possibleFriends yang berkurang. Jika Anda masuk ke HomeScreen, Anda akan melihat jumlah teman bertambah.

      Kini Anda dapat melakukan navigasi di antara layar dan berbagi data.

      Kesimpulan

      Dalam tutorial ini, Anda telah membuat aplikasi sampel React Native dengan beberapa layar. Dengan menggunakan React Navigation, Anda telah membuat cara navigasi di antara layar. Dengan React Context, Anda mengembangkan cara berbagi data di antara beberapa layar.

      Kode sumber lengkap untuk tutorial ini tersedia di GitHub.

      Jika Anda ingin lebih mendalami React Navigation, lihat dokumentasinya.

      React Navigation bukan satu-satunya solusi perutean dan navigasi. Ada juga React Native Navigation, React Native Router Flux, dan React Router Native.

      Jika Anda ingin mempelajari lebih lanjut tentang React, lihat seri Cara Melakukan Pengodean di React.js dari kami, atau baca halaman topik React kami untuk proyek pemrograman dan latihan.



      Source link

      Comment utiliser le routage avec React Navigation dans React Native


      Introduction

      React Navigation est une bibliothèque populaire pour le routage et la navigation dans une application React Native.

      Cette bibliothèque aide à résoudre le problème de la navigation entre plusieurs écrans et du partage des données entre eux.

      À la fin de ce tutoriel, vous disposerez d’un réseau social rudimentaire. Il affichera le nombre de connexions dont dispose un utilisateur et fournira un moyen de se connecter avec des amis supplémentaires. Vous utiliserez cet exemple d’application pour découvrir comment naviguer dans les écrans d’applications mobiles en utilisant react-navigation.

      Conditions préalables

      Pour suivre ce tutoriel, vous aurez besoin des éléments suivants :

      Remarque : Si vous avez travaillé avec react-navigation auparavant, vous pourriez rencontrer certaines différences. Vous pouvez consulter la documentation pour les guides pour migrer de 3.x et migrer de 4.x.

      Ce tutoriel a été vérifié avec Node v14.7.0, npm v6.14.7, react v16.13.1, react-native v0.63.2, @react-navigation/native v5.7.3 et @react-navigation/stack v5.9.0.

      Étape 1 – Création d’une nouvelle application React Native

      Tout d’abord, créez une nouvelle application React Native en entrant la commande suivante dans votre terminal :

      • npx react-native init MySocialNetwork --version 0.63.2

      Ensuite, naviguez vers le nouveau répertoire :

      Et lancez l'application pour iOS :

      Ou alors, pour Android :

      Note : Si vous rencontrez des problèmes, vous devrez peut-être consulter Résolution de problèmes pour React Native CLI.

      Cela permettra de créer un projet squelette pour vous. Il ne ressemble pas beaucoup à un réseau social pour l'instant. Réglons ça.

      Ouvrez App.js :

      Remplacez le contenu d’App.js avec le code suivant pour afficher un message de bienvenue :

      App.js

      import React from 'react';
      import { StyleSheet, Text, View } from 'react-native';
      
      class App extends React.Component {
        render() {
          return (
            <View style={styles.container}>
              <Text>Welcome to MySocialNetwork!</Text>
            </View>
          );
        }
      }
      
      const styles = StyleSheet.create({
        container: {
          flex: 1,
          backgroundColor: '#fff',
          alignItems: 'center',
          justifyContent: 'center',
        },
      });
      
      export default App;
      

      Sauvegardez le fichier. Maintenant, lorsque vous exécutez l'application, un Welcome to MySocialNetwork! MySocialNetwork! apparaîtra dans votre simulateur.

      Dans l'étape suivante, vous ajouterez d'autres écrans à votre application.

      Étape 2 - Création d'un HomeScreen et FriendsScreen

      Actuellement, vous disposez d'un seul écran affichant un message de bienvenue. Au cours de cette étape, vous créerez les deux écrans de votre application : HomeScreen et FriendsScreen.

      HomeScreen

      Votre application aura besoin d'un HomeScreen. Le HomeScreen affichera le nombre d'amis déjà présents dans votre réseau.

      Prenez le code d’App.js et ajoutez-le à un nouveau fichier appelé HomeScreen.js :

      Ouvrez HomeScreen.js:

      Modifiez HomeScreen.js pour utiliser HomeScreen au lieu d’App :

      HomeScreen.js

      import React from 'react';
      import { StyleSheet, Text, View } from 'react-native';
      
      class HomeScreen extends React.Component {
        render() {
          return (
            <View style={styles.container}>
              <Text>You have (undefined) friends.</Text>
            </View>
          );
        }
      }
      
      // ...
      
      export default HomeScreen;
      

      Ce code produira un message de remplacement You have (undefined) friends. Vous fournirez une valeur plus tard.

      FriendsScreen

      Votre application aura également besoin d'un FriendsScreen. Sur le FriendsScreen, vous pourrez ajouter de nouveaux amis.

      Prenez le code de App.js et ajoutez-le à un nouveau fichier appelé FriendsScreen.js :

      • cp App.js FriendsScreen.js

      Ouvrez FriendsScreen.js :

      Modifiez FriendsScreen.js pour utiliser FriendsScreen au lieu d’App :

      FriendsScreen.js

      import React from 'react';
      import { StyleSheet, Text, View } from 'react-native';
      
      class FriendsScreen extends React.Component {
        render() {
          return (
            <View style={styles.container}>
              <Text>Add friends here!</Text>
            </View>
          );
        }
      }
      
      // ...
      
      export default FriendsScreen;
      

      Ce code produira un Add friends here! here!

      À ce stade, vous avez un HomeScreen et FriendsScreen. Cependant, il n'y a pas moyen de naviguer entre eux. Vous développerez cette fonctionnalité au cours de la prochaine étape.

      Étape 3 - Utilisation des StackNavigator avec React Navigation

      Pour naviguer entre les écrans, vous utiliserez un StackNavigator. Un StackNavigator fonctionne exactement comme une pile d'appels. Chaque écran vers lequel vous naviguez est poussé vers le haut de la pile. Chaque fois que vous appuyez sur le bouton Retour, les écrans se détachent du haut de la pile.

      Tout d'abord, installez @react-navigation/native :

      • npm install @react-navigation/native@5.7.3

      Ensuite, installez @react-navigation/stack et ses dépendances :

      • npm install @react-navigation/stack@5.9.0 @react-native-community/masked-view@0.1.10 react-native-screens@2.10.1 react-native-safe-area-context@3.1.4 react-native-gesture-handler@1.7.0

      Remarque : Si vous développez pour iOS, vous pouvez avoir besoin de naviguer vers le répertoireios et exécuter pod install.

      Ensuite, revisitez App.js :

      Ajoutez NavigationContainer et createStackNavigator à App.js :

      App.js

      import 'react-native-gesture-handler';
      import React from 'react';
      import { StyleSheet } from 'react-native';
      import { NavigationContainer } from '@react-navigation/native';
      import { createStackNavigator } from '@react-navigation/stack';
      
      const Stack = createStackNavigator();
      

      Ensuite, remplacez le contenu de render :

      App.js

      // ...
      
      class App extends React.Component {
        render() {
          return (
            <NavigationContainer>
              <Stack.Navigator>
              </Stack.Navigator>
            </NavigationContainer>
          );
        }
      }
      
      // ...
      

      Nichée à l'intérieur <Stack.Navigator>, ajoutez le HomeScreen :

      App.js

      import 'react-native-gesture-handler';
      import React from 'react';
      import { StyleSheet } from 'react-native';
      import { NavigationContainer } from '@react-navigation/native';
      import { createStackNavigator } from '@react-navigation/stack';
      import HomeScreen from './HomeScreen';
      
      const Stack = createStackNavigator();
      
      class App extends React.Component {
        render() {
          return (
            <NavigationContainer>
              <Stack.Navigator>
                <Stack.Screen
                  name="Home"
                  component={HomeScreen}
                />
              </Stack.Navigator>
            </NavigationContainer>
          );
        }
      }
      
      // ...
      

      Ce code crée une très petite pile pour votre navigateur avec un seul écran : HomeScreen.

      Nichée à l'intérieur <Stack.Navigator>, ajoutez le FriendsScreen :

      App.js

      import 'react-native-gesture-handler';
      import React from 'react';
      import { StyleSheet } from 'react-native';
      import { NavigationContainer } from '@react-navigation/native';
      import { createStackNavigator } from '@react-navigation/stack';
      import HomeScreen from './HomeScreen';
      import FriendsScreen from './FriendsScreen';
      
      const Stack = createStackNavigator();
      
      class App extends React.Component {
        render() {
          return (
            <NavigationContainer>
              <Stack.Navigator>
                <Stack.Screen
                  name="Home"
                  component={HomeScreen}
                />
                <Stack.Screen
                  name="Friends"
                  component={FriendsScreen}
                />
              </Stack.Navigator>
            </NavigationContainer>
          );
        }
      }
      
      // ...
      

      Ce code ajoute le FriendsScreen au navigateur.

      Remarque : Cela diffère de la façon dont createStackNavigator a été utilisé dans les versions précédentes de React Navigation.

      Maintenant, le navigateur est conscient de vos deux écrans.

      Ajouter des boutons à HomeScreen et FriendsScreen

      Enfin, ajoutez des boutons pour vous déplacer entre vos deux écrans.

      Dans HomeScreen.js, ajoutez le code suivant :

      HomeScreen.js

      import React from 'react';
      import { StyleSheet, Text, View, Button } from 'react-native';
      
      class HomeScreen extends React.Component {
        render() {
          return (
            <View style={styles.container}>
              <Text>You have (undefined) friends.</Text>
      
              <Button
                title="Add some friends"
                onPress={() =>
                  this.props.navigation.navigate('Friends')
                }
              />
            </View>
          );
        }
      }
      
      // ...
      

      Dans FriendsScreen.js, ajoutez le code suivant :

      FriendsScreen.js

      import React from 'react';
      import { StyleSheet, Text, View, Button } from 'react-native';
      
      class FriendsScreen extends React.Component {
        render() {
          return (
            <View style={styles.container}>
              <Text>Add friends here!</Text>
      
              <Button
                title="Back to home"
                onPress={() =>
                  this.props.navigation.navigate('Home')
                }
              />
            </View>
          );
        }
      }
      
      // ...
      

      Parlons de this.props.navigation. Tant que votre écran est inclus dans le StackNavigatorIl hérite automatiquement de nombreux accessoires utiles de la navigation objet. Dans ce cas, vous avez utilisé navigate pour passer à une autre page.

      HomeScreen et FriendsScreen

      Si vous ouvrez maintenant votre simulateur, vous pouvez naviguer entre le HomeScreen et le FriendsScreen.

      Étape 4 - Utilisation de Context pour transmettre des données à d'autres écrans

      Dans cette étape, vous allez créer un ensemble d'amis possibles - Alice, Bob et Sammy - et une série vide d'amis actuels. Vous créerez également une fonctionnalité permettant à l'utilisateur d'ajouter des amis possibles à ses amis actuels.

      Ouvrez App.js : 

      Ajoutez possibleFriends et currentFriends à l'état du composant :

      App.js

      // ...
      
      class App extends React.Component {
        constructor(props) {
          super(props)
          this.state = {
            possibleFriends: [
              'Alice',
              'Bob',
              'Sammy',
            ],
            currentFriends: [],
          }
        }
      
        // ...
      }
      
      // ...
      

      Ensuite, ajoutez une fonction permettant de déplacer un ami éventuel dans la liste des amis actuels :

      App.js

      // ...
      
      class App extends React.Component {
        constructor(props) {
          super(props)
          this.state = {
            possibleFriends: [
              'Alice',
              'Bob',
              'Sammy',
            ],
            currentFriends: [],
          }
        }
      
        addFriend = (index) => {
          const {
            currentFriends,
            possibleFriends,
          } = this.state
      
          // Pull friend out of possibleFriends
          const addedFriend = possibleFriends.splice(index, 1)
      
          // And put friend in currentFriends
          currentFriends.push(addedFriend)
      
          // Finally, update the app state
          this.setState({
            currentFriends,
            possibleFriends,
          })
        }
      
        // ...
      }
      
      // ...
      

      À ce stade, vous avez terminé la construction de la fonctionnalité permettant d'ajouter des amis.

      Ajouter FriendsContext à App

      Vous pouvez maintenant ajouter des amis dans App.jsmais vous voudrez les ajouter à FriendsScreen.js et les faire afficher dans HomeScreen.js. Comme ce projet est construit avec React, vous pouvez injecter cette fonctionnalité dans vos écrans avec context.

      Note : Dans les versions précédentes de React Navigation, il était possible d'utiliser screenProps pour partager les données entre les écrans. Dans la version actuelle de React Navigation, il est recommandé d'utiliser React Context pour partager les données entre les écrans.

      Pour éviter une référence circulaire, vous voudrez un nouveau fichier FriendsContext :

      Exportez FriendsContext :

      FriendsContext

      import React from 'react';
      
      export const FriendsContext = React.createContext();
      

      Ouvrez App.js : 

      Ajoutez le FriendsContext :

      App.js

      import 'react-native-gesture-handler';
      import React from 'react';
      import { StyleSheet } from 'react-native';
      import { NavigationContainer } from '@react-navigation/native';
      import { createStackNavigator } from '@react-navigation/stack';
      import { FriendsContext } from './FriendsContext';
      import Home from './Home';
      import Friends from './Friends';
      
      const Stack = createStackNavigator();
      
      class App extends React.Component {
        // ...
      
        render() {
          return (
            <FriendsContext.Provider>
              <NavigationContainer>
                <Stack.Navigator>
                  <Stack.Screen
                    name="Home"
                    component={Home}
                  />
                  <Stack.Screen
                    name="Friends"
                    component={Friends}
                  />
                </Stack.Navigator>
              </NavigationContainer>
            </FriendsContext.Provider>
          );
        }
      }
      
      // ...
      

      Ce code établit FriendsContext comme nouvel objet Context et enveloppe le NavigationContainer dans un Context.Provider afin que tous les enfants de l'arbre des composants puissent s'abonner aux changements de contexte.

      Puisque vous n'utilisez plus View ou Text, il est possible de supprimer ces importations de react-native.

      Vous devrez fournir une valeur pour rendre les données accessibles aux consommateurs :

      App.js

      // ...
      
      class App extends React.Component {
        // ...
      
        render() {
          return (
            <FriendsContext.Provider
              value={
                {
                  currentFriends: this.state.currentFriends,
                  possibleFriends: this.state.possibleFriends,
                  addFriend: this.addFriend
                }
              }
            >
              <NavigationContainer>
                <Stack.Navigator>
                  <Stack.Screen
                    name="Home"
                    component={Home}
                  />
                  <Stack.Screen
                    name="Friends"
                    component={Friends}
                  />
                </Stack.Navigator>
              </NavigationContainer>
            </FriendsContext.Provider>
          );
        }
      }
      
      // ...
      

      Cela permettra à la HomeScreen et FriendsScreen de référencer tout changement de contexte currentFriends et possibleFriends.

      Vous pouvez maintenant travailler sur le référencement du contexte dans vos écrans.

      Ajouter FriendsContext à HomeScreen

      Dans cette étape, vous configurerez l'application pour afficher le nombre actuel d'amis.

      Ouvrez HomeScreen.js :

      Et ajoutez le FriendsContext :

      HomeScreen.js

      import React from 'react';
      import { StyleSheet, Text, View, Button } from 'react-native';
      import { FriendsContext } from './FriendsContext';
      
      class HomeScreen extends React.Component {
        // ...
      }
      HomeScreen.contextType = FriendsContext;
      
      // ...
      

      Ce code établit un Classe.contexteType. Vous pouvez maintenant accéder au contexte dans vos écrans.

      Par exemple, faisons en sorte que votre HomeScreen affiche combien de currentFriends vous avez :

      HomeScreen.js

      import React from 'react';
      import { StyleSheet, Text, View, Button } from 'react-native';
      import { FriendsContext } from './FriendsContext';
      
      class Home extends React.Component {
        render() {
          return (
            <View style={styles.container}>
              <Text>You have { this.context.currentFriends.length } friends!</Text>
      
              <Button
                title="Add some friends"
                onPress={() =>
                  this.props.navigation.navigate('Friends')
                }
              />
            </View>
          );
        }
      }
      HomeScreen.contextType = FriendsContext;
      
      // ...
      

      Si vous ouvrez à nouveau votre application dans le simulateur et que vous visualisez le HomeScreenvous verrez le message : You have 0 friends!

      Ajoutez FriendsContext à FriendsScreen

      Dans cette étape, vous configurerez l'application pour afficher les amis possibles et fournir des boutons pour les ajouter aux amis actuels.

      Ensuite, ouvrez FriendsScreen.js :

      Et ajoutez le FriendsContext :

      FriendsScreen.js

      import React from 'react';
      import { StyleSheet, Text, View, Button } from 'react-native';
      import { FriendsContext } from './FriendsContext';
      
      class FriendsScreen extends React.Component {
        // ...
      }
      FriendsScreen.contextType = FriendsContext;
      
      // ...
      

      Ce code établit un Class.contextType.

      Maintenant, créez un bouton pour ajouter des amis dans FriendsScreen.js :

      FriendsScreen.js

      import React from 'react';
      import { StyleSheet, Text, View, Button } from 'react-native';
      import { FriendsContext } from './FriendsContext';
      
      class Friends extends React.Component {
        render() {
          return (
            <View style={styles.container}>
              <Text>Add friends here!</Text>
      
              {
                this.context.possibleFriends.map((friend, index) => (
                  <Button
                    key={ friend }
                    title={ `Add ${ friend }` }
                    onPress={() =>
                      this.context.addFriend(index)
                    }
                  />
                ))
              }
      
              <Button
                title="Back to home"
                onPress={() =>
                  this.props.navigation.navigate('Home')
                }
              />
            </View>
          );
        }
      }
      FriendsScreen.contextType = FriendsContext;
      
      // ...
      

      Si vous ouvrez à nouveau votre application dans le simulateur et que vous visualisez le FriendsScreen, vous verrez une liste d'amis à ajouter.

      HomeScreen avec 0 currentFriends et FriendsScreen avec 3 possibleFriends

      Si vous visitez le FriendsScreen et cliquez sur le bouton pour ajouter des amis, vous verrez la liste des possibleFriends diminuer. Si vous visitez le HomeScreen, vous verrez le nombre d'amis augmenter.

      Vous pouvez désormais naviguer entre les écrans et partager des données entre eux.

      Conclusion

      Dans ce tutoriel, vous avez créé un exemple d'application React Native avec plusieurs écrans. En utilisant React Navigation, vous avez imaginé un moyen de naviguer entre les écrans. En utilisant React Context, vous avez développé un moyen de partager des données entre les écrans.

      L'ensemble du code source de ce tutoriel est disponible sur GitHub.

      Si vous souhaitez approfondir votre connaissance de React Navigation, consultez leur documentation.

      React Navigation n'est pas la seule solution de routage et de navigation. Il y a aussi React Native Navigation, React Native Router Fluxet React Router Native.

      Si vous souhaitez en savoir plus sur React, consultez notre série Comment coder dans React.js ou consultez notre page thématique React pour des exercices et des projets de programmation.



      Source link