One place for hosting & domains

      Cases

      Your Guide to Common Redirects (+ Use Cases)


      When updating your website’s content, you may find that you’ve accidentally created some broken links. That’s okay, it happens!

      You see, when a URL changes and it’s not properly redirected, it will cause those broken links, also known as 404 Errors. These issues harm user experience and Search Engine Optimization (SEO).

      The good news is that you can use redirects to fix broken links by rerouting traffic from old content to new web pages. In this way, you can optimize your website’s structure and avoid common front-end errors.

      This post will discuss what redirects are and when you might consider using them. Then we’ll give you an overview of the basic redirect types and explain how you can implement them on your website. Ready?

      An Introduction to Redirects

      A redirect is a method that takes users visiting an old URL and sends them to a new page. Whenever a visitor clicks on the original URL, the redirect takes them to the relevant, updated page the site owner wants them to find instead.

      One of the main reasons to use a redirect is to prevent visitors from seeing error pages. For example, if there are any broken links on your site, users may see a 404 error instead of the content they came for. This is also known as a 404 (Page Not Found) error:

      404 error page

      After encountering a 404 message, visitors are more likely to leave your website. This is not ideal under any circumstances. Plus, a higher bounce rate can harm your SEO.

      However, you can avoid these issues by using a redirect. You can send users to relevant content even after the URL changes. Here are some instances when you might need to redirect a link:

      Redirects can offer many benefits, but only when used correctly. Therefore, it’s important to consider some redirect best practices. That way, you can avoid common mistakes.

      For example, ‘redirect chains’ occur when there are multiple redirects going from the original content to the final URL. This can increase page loading time, decrease link equity, and negatively impact SEO.

      If your content has a redirect loop, this means there are multiple redirects that eventually lead back to the original URL. As a result, visitors may end up waiting longer for the same error message instead of your content.

      To check your website for redirect chains and loops, you can use a platform such as Screaming Frog. This tool provides a website crawler that can audit redirects:

      Screaming Frog SEO SPider

      With Screaming Frog’s SEO Spider, you can bulk check your redirects. Using this tool, you can identify any redirect loops or chains and use a new redirect to fix any problems.

      6 Types of URL Redirects (And Why You Might Use Them)

      Now that you know the basics of URL redirects, let’s discuss the available different types. That way, you can choose the best option for your website.

      301 Redirect

      A 301 redirect is a permanent redirect from a deleted or moved web page. This is one of the most common redirect types.

      Since a 301 redirect is permanent, you’ll want to use this option only when you don’t need to access the original content again. When you implement a 301 redirect, its code informs search engine crawlers that certain content has been removed and no longer needs to be indexed.

      You should consider using a 301 redirect when:

      • Permanently deleting a website page
      • Moving your website to a new domain
      • Changing a page URL by shortening or cloaking links
      • Consolidating multiple pieces of content into a combined web page

      A 301 redirect can be very useful for improving the user experience on your website. With it, you can permanently prevent users from seeing a 404 error page.

      For instance, if one of your products is no longer available, you could redirect traffic to your other product collections. This can keep visitors on your website by giving them similar recommendations:

      product recommendations page

      This tactic may also benefit your SEO. For instance, with 301 redirects, you can merge multiple pieces of thin content into a single in-depth resource. This is a smart way to repurpose content and improve underperforming web pages.

      302 Redirect

      A 302 redirect is similar to a 301, except that it’s a temporary redirect. It indicates that the original content has been temporarily moved to a new URL.

      On the browser side (i.e., from the user’s perspective), there isn’t much difference between a 302 and 301 redirect. However, a 302 redirect has a different HTTP response status code. This code informs search engines not to update their links to the original resource.

      Consider using a 302 redirect when:

      • Making changes to the original content
      • Performing A/B testing
      • Informing your audience about sold-out products

      302 redirects can often improve user experience by keeping visitors informed about website changes and updates. For example, you could temporarily redirect to a countdown page when relaunching a product:

      countdown page

      The best part about 302 redirects is that you can return to the original content at a later time. So rather than permanently preventing search engines and viewers from seeing certain pages, you can simply redirect to a temporary stand-in page.

      303 Redirect

      A 303 redirect is an HTTP response status code that means “see other.” Similar to a 302 redirect, it is a temporary code that informs the browser and search engine that the original content was replaced with a similar resource.

      The main difference between 303 and 302 redirects is that a 303 is not cacheable. This can be useful if you don’t want Google to store a certain web page over the long term.

      303 redirects are useful for rerouting after PUT or POST request methods. This ensures that refreshing the page doesn’t trigger the redirect again.

      For example, you can use a 303 redirect to handle form submissions. These are commonly used to redirect to thank you pages after entries:

      form submission success page

      After a visitor completes the form, a 303 redirect won’t allow them to use the back button to refresh the page. By using this redirect, you can avoid receiving duplicate form submissions.

      307 Redirect

      Another temporary option is the 307 redirect. This is a server-side redirect that informs search engines that you might change the URL in the future. What makes a 307 redirect unique is that it requires the HTTP request method to stay consistent.

      Although they are similar to 302 redirects, 307 redirects can be more clear. That’s because a 307 redirect doesn’t allow conversions from the POST to the GET request method.

      You may want to use a 307 redirect when running a recurring promotion or giveaway. This can be useful for performing frequent URL updates:

      example of online sweepstakes web page

      A 307 redirect can enable you to periodically update a link’s content while still using the original URL. This way, you can avoid losing any web traffic.

      308 Redirect

      Similar to a 301 redirect, a 308 redirect indicates that the original URL is being permanently relocated. However, 308 redirects don’t allow changing the request method from POST to GET.

      You can use 308 redirects for all the same 301 redirect use cases, such as when permanently moving a resource to a new location. Additionally, a 308 redirect can come in handy when you’re migrating a website that contains many forms created via the POST method.

      Additionally, using a 308 redirect can give you greater control over browser requests. Since you can specify either a POST or GET request method, this can often be cleaner and more efficient than 301 redirects.

      Meta Refresh

      Unlike the other methods on this list, a meta refresh is a client-side redirect. Instead of redirecting on the web server, this happens in the web browser. You might recognize this redirect as a refresh countdown timer on certain pages:

      meta refresh temporary web page

      You can use this type of redirect to refresh a web page that a visitor is already on. This can be beneficial for updating dynamic web pages such as online auctions.

      Unfortunately, implementing a meta refresh can also come with some downsides. When you use this technique, search engines could possibly flag your website as spam. Also, meta refreshes can impact user experience due to increased loading times.

      Skip the line and get tips right in your inbox

      Click below to sign up for more how-to’s and tutorials just like this one, delivered to your inbox.

      marketing tips

      How to Implement Redirects (3 Methods)

      Each redirect type can offer specific benefits to your website. As such, you’ll want to carefully consider which is the most appropriate redirect for your goals. Then, you can easily implement your redirects via one of the following methods.

      1. Use a WordPress Redirect Plugin

      WordPress is open-source software, and web developers are always creating new plugins to enhance its functionality. For WordPress website owners, a redirect plugin is one of the simplest ways to create your redirects.

      If this option appeals to you, we’d recommend downloading and installing the Redirection plugin. This is a free tool that enables you to manage all of your redirects in one place:

      WordPress Redirection plugin page

      If you use this plugin, you won’t have to rely on complicated coding. As long as your WordPress website supports permalinks, you can use Redirection to scan for broken links and fix them with redirects.

      To get started, navigate to your WordPress dashboard. Then go to Plugins > Add New. Look for the Redirection plugin using the search tool. When you find it, simply install and activate it:

      install Redirection page

      Next, go to Tools > Redirection. This will allow you to create new redirects or edit existing ones:

      add new redirect

      Click on Add New, and enter both the source URL and the target URL:

      add new 301 redirect Redirection

      Then, find HTTP code in the advanced options and pick from the list of redirect types. You’ll be able to choose from 301, 302, 303, 304, 307, and 308 redirects:

      Redirection plugin advanced options screen

      When you’re finished customizing your redirect, click on Add Redirect. It’s as simple as that!

      2. Create a Redirect Using Your .htaccess File

      .htaccess is a configuration file that you can use to make changes to your server software. Using this method, you can redirect certain URLs, make custom 404 error pages, and change your permalinks from HTTP to HTTPS. However, this file is only accessible on Apache servers.

      You can find your .htaccess file in your website’s root folder. Exactly how you access this will depend on your web host and plan. If you have a plan here at DreamHost, you can access your account, select the site you want to work with, and go to Manage Files. Look for the folder named after your site and click on it:

      .htaccess redirect

      Then locate the .htaccess file. Right-click on it, and choose Edit:

      .htaccess redirect

      Use the text editor to add your redirect code. If you’re redirecting from one internal page to another, here is the basic formatting you should use:

      Redirect [redirect type] [/path/to/old/file/old.html] [/path/to/new/file/new.html]

      If redirecting to an external page, replace the final part with the full URL for the page you want to send visitors to.

      For example, we implemented a 302 redirect. This is what our .htaccess code looked like:

      example .htaccess file

      If you’re implementing a meta refresh, you can use this code instead:

      <meta http-equiv="refresh" content="2;url=http://example.com/" />

      Once you’ve finished, click on Save & Close. Then you’ll probably want to check your work. To do this, simply visit the old URL in a browser to see if it directs to the new page.

      3. Make a Redirect in Your PHP file

      Another easy way to implement a redirect is by using PHP. This involves adding the header () function to a PHP file to direct visitors to a new URL. However, your original source will need to be a PHP file for this process to work.

      To get started, open a text editor. For those using a Microsoft computer, we’d recommend Notepad++. For Mac users, Tumult Whisk is a good alternative.

      Then, make sure the language is set to PHP. Open your source PHP file, and add your redirect code as the first line of the document. For example, a 301 redirect source code looks like this:

      <?php
      header("HTTP/1.1 301 Moved Permanently");
      header("Location: https://www.domain.com/the-new-name.php");
      header("Connection: close");
      ?>

      Remember that if you don’t define your 301 redirect in the header, it will automatically default to a 302 redirect. When you’re finished, save the file and test your results by visiting the old link.

      A Solution to Broken Links

      Broken links may increase your website’s bounce rate, but you can avoid this problem by using redirects. While 301 redirects are the most common solution for rerouting traffic, there are many other temporary options. By choosing the right redirect, you can avoid displaying 404 error pages and keep visitors on your website longer.

      With DreamHost, you can avoid this kind of complicated website management. We offer professional website management services that leave any technical problems to the experts. Check out our plans today to ensure that all your pages are primed for peak performance!

      Website Management Made Easy

      Let us handle the backend — we’ll manage and monitor your website so it’s safe, secure, and always up.

      DreamCare website tech support



      Source link

      How To Use Downshift in Common Dropdown Use Cases


      Introduction

      Downshift is a library that helps you build simple, flexible, WAI-ARIA compliant enhanced input React components. Its major use case is for building autocomplete components, but it can also be used to build dropdown components.

      In this tutorial, we’ll walk through some common use cases solved with Downshift.

      Prerequisites

      To follow this tutorial, you need Node and NPM installed on your machine. A basic understanding of React will help you get the most out of this tutorial.

      If you don’t have Node.js installed, go to the Node website and install the recommended version for your operating system.

      Step 1 — Setting Up the Application

      We’ll make use of Create React App to create a simple React app with no build configuration. If you don’t have Create React App installed, run npm i create-react-app in your terminal to install it.
      Once you have it on your machine, run the following command to set up a new React project in a directory called downshift-examples and move to this new directory by running these commands:

      • create-react-app downshift-examples
      • cd downshift-examples

      Once you’re in the downshift-examples directory, run the following command to install Downshift and some other packages:

      • yarn add downshift axios react-popper

      Open the App.css file in the src folder and add the following styles:

      src/App.css

          input {
            margin: 1rem;
            width: 20rem;
            padding: 1rem .5rem;
          }
          .downshift-dropdown {
            margin: 0 auto;
            width: 20rem;
            border: 1px solid whitesmoke;
            border-bottom: none;
          }
          .dropdown-item {
            padding: 0.5rem;
            cursor: pointer;
            border-bottom: 1px solid whitesmoke;
            font-size: 1rem;
            text-align: left;
          }
          .dropdown-button {
            padding: 0.6rem;
            border-radius: 3px;
            background: white;
            cursor: pointer;
          }
          .popper-div {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 5rem;
          }
          .popper-item {
            padding: .5rem;
            border-bottom: 1px solid whitesmoke;
          }
      

      With everything set up, let’s look at some basic Downshift concepts.

      Overview of Downshift Concepts

      When using Downshift, the only component we need is <Downshift />. We call the <Downshift /> component and pass it some props and it works its magic. Here are some of the most used props:

      1. onChange: This function is called when the user selects an item and the selected item has changed. It returns the selectedItem.
      2. itemToString: This function is used to determine the string value for the selected item which is used to compute the inputValue.
      3. inputValue: This represents the value the input field should have.
      4. getInputProps: This function returns the props you should apply to the input element that you render.
      5. getItemProps: This function returns the props you should apply to any menu item elements you render.
      6. isOpen: This is a boolean that indicates whether or not the menu is open.
      7. selectedItem: This represents the currently selected item input.
      8. render: This is where you render whatever you want to based on the state of Downshift. This function is called with an object.

      You can check the documentation for the full list of props. Now let’s put this knowledge to use.

      Step 2 — Creating a Select Field

      Our first Downshift use case is a select field. Go ahead and create a DownshiftOne.js file in the src folder in the root directory of your app. Add the following code to it:

      src/DownshiftOne.js

          import React from 'react'
          import Downshift from 'downshift';
      
          const books = [
            { name: 'Harry Potter' },
            { name: 'Net Moves' },
            { name: 'Half of a yellow sun' },
            { name: 'The Da Vinci Code' },
            { name: 'Born a crime' },
          ];
      
          const onChange = (selectedBook) => {
            alert(`your favourite book is ${selectedBook.name}`)
          }
      
          export default () => {
            return (
              <Downshift onChange={onChange} itemToString={books => (books ? books.name : '')}>
                {/* we'll insert a callback here */}
              </DownShift>
            )
          }
      

      In the code above, we import React and Downshift and declare an array of books, an onChange function, and also a functional component that returns the <Downshift/> component. In the <Downshift/> component, we pass the onChange and itemToString props. Inside the <Downshift/> component, we’ll pass other props to a callback and render our input field.

      Next, we’ll pass the props we need in a callback to the <Downshift/> component. Update your functional component with the following:

      src/DownshiftOne.js

          ...
      
          export default () => {
            return (
              <Downshift onChange={onChange} itemToString={books => (books ? books.name : '')}>
                // pass the downshift props into a callback
                {({ getInputProps, getItemProps, isOpen, inputValue, highlightedIndex, selectedItem, getLabelProps }) => (
                  <div>
                    // add a label tag and pass our label text to the getLabelProps function
                    <label style={{ marginTop: '1rem', display: 'block' }} {...getLabelProps()}>Choose your favourite book</label> <br />
                    // add our input element and pass our placeholder to the getInputProps function
                    <input {...getInputProps({ placeholder: "Search books" })} />
                    // if the input element is open, render the div else render nothing
                    {isOpen ? (
                      <div className="downshift-dropdown">
                        {
                          // filter the books and return items that match the inputValue
                          books
                            .filter(item => !inputValue || item.name.toLowerCase().includes(inputValue.toLowerCase()))
                            // map the return value and return a div
                            .map((item, index) => (
                              <div
                                className="dropdown-item"
                                {...getItemProps({ key: item.name, index, item })}
                                style={{
                                  backgroundColor: highlightedIndex === index ? 'lightgray' : 'white',
                                  fontWeight: selectedItem === item ? 'bold' : 'normal',
                                }}>
                                {item.name}
                              </div>
                            ))
                        }
                      </div>
                    ) : null}
                  </div>
                )}
              </Downshift>
            )
          }
      

      In the code snippet above, we passed our Downshift props as parameters to a callback:

          {({ getInputProps, getItemProps, isOpen, inputValue, highlightedIndex, selectedItem, getLabelProps }) => ()}
      

      In the callback, we add our input tag and pass it our getInputProps props:

          <input {...getInputProps({ placeholder: "Search books" })} />
      

      Next, we check if the input element is open. If it is, we return a div element containing our menu and return null if it’s not:

          { isOpen ? (<div className="downshift-dropdown">...</div>) : null }
      

      Lastly, in the div element which we’re returning, we filter through our books array, returning only the items that include the inputValue. We then map through the filtered books and render them on the page.

      We also passed the getItemProps function to the div rendered in the map function. It returns the props that we applied while rendering the items.

      Let’s import our component to the parent App component, and see our functional select field:

      src/App.js

          import React, { Component } from 'react';
          import logo from './logo.svg';
          import './App.css';
          import DownshiftOne from './DownshiftOne'; // import the component
      
          class App extends Component {
            render() {
              return (
                <div className="App">
                  <header className="App-header">
                    <img src={logo} className="App-logo" alt="logo" />
                    <h1 className="App-title">Welcome to React</h1>
                  </header>
                  <DownshiftOne /> // render the component
                </div>
              );
            }
          }
          export default App;
      

      Ensure your server is running by running npm start in your terminal. If you open http://localhost:3000 in your browser, you will see the app running.

      Step 3 — Using Downshift with Axios

      In our next example, we’ll use Downshift to create a search field for movies. In the src folder, create a DownshiftTwo.js file and add the following code:

      src/DownshiftTwo.js

          import React, { Component } from 'react'
          import Downshift from 'downshift';
          import axios from 'axios';
      
          export default class DownshiftTwo extends Component {
            constructor(props) {
              super(props)
              this.state = {
                movies: []
              }
              this.fetchMovies = this.fetchMovies.bind(this)
              this.inputOnChange = this.inputOnChange.bind(this)
            }
            // onChange method for the input field
            inputOnChange(event) {
              if (!event.target.value) {
                return
              }
              this.fetchMovies(event.target.value)
            }
            // input field for the <Downshift /> component
            downshiftOnChange(selectedMovie) {
              alert(`your favourite movie is ${selectedMovie.title}`)
            }
            // method to fetch the movies from the movies API
            fetchMovies(movie) {
              const moviesURL = `https://api.themoviedb.org/3/search/movie?api_key=APIKey&query=${movie}`;
              axios.get(moviesURL).then(response => {
                this.setState({ movies: response.data.results })
              })
            }
            render() {
              return (
                <Downshift onChange={this.downshiftOnChange} itemToString={item => (item ? item.title : '')}>
                // pass the downshift props into a callback
                  {({ selectedItem, getInputProps, getItemProps, highlightedIndex, isOpen, inputValue, getLabelProps }) => (
                    <div>
                      // add a label tag and pass our label text to the getLabelProps function
                      <label style={{ marginTop: '1rem', display: 'block' }} {...getLabelProps()}>Choose your favourite movie</label> <br />
                      // add a input tag and pass our placeholder text to the getInputProps function. We also have an onChange eventlistener on the input field
                      <input {...getInputProps({
                        placeholder: "Search movies",
                        onChange: this.inputOnChange
                      })} />
                      // if the input element is open, render the div else render nothing
                      {isOpen ? (
                        <div className="downshift-dropdown">
                          {
                            // filter the movies in the state
                            this.state.movies
                              .filter(item => !inputValue || item.title.toLowerCase().includes(inputValue.toLowerCase()))
                              .slice(0, 10) // return just the first ten. Helps improve performance
                              // map the filtered movies and display their title
                              .map((item, index) => (
                                <div
                                  className="dropdown-item"
                                  {...getItemProps({ key: index, index, item })}
                                  style={{
                                    backgroundColor: highlightedIndex === index ? 'lightgray' : 'white',
                                    fontWeight: selectedItem === item ? 'bold' : 'normal',
                                  }}>
                                  {item.title}
                                </div>
                              ))
                          }
                        </div>
                      ) : null}
                    </div>
                  )}
                </Downshift>
              )
            }
          }
      

      In the code above, we have a class component where we’re rendering the <Downshift/> component and passing our props to it. In the input field in the <Downshift/> component, we have an onChange event listener that listens for new input to the field.

      If there’s an input, we call the fetchMovies method which takes the value of the input field and makes an AJAX request to the movies API using Axios. We set the request response to the component state, then filter through them to return the matching item as done in the previous example.

      Import and render the component in the parent App component as we did in the previous example. Visit your browser and try searching for your favorite movie.

      Step 4 — Creating a Dropdown with Downshift

      One other use case for Downshift is powering dropdowns. Dropdown’s API helps us build simple dropdown components. Let’s create a DownshiftThree.js file in the src folder and see how to achieve this.

      In the DownshiftThree.js file, add the following code:

      src/DownshiftThree.js

          import React, { Component } from 'react'
          import Downshift from 'downshift';
      
          export default class DownshiftThree extends Component {
            constructor(props) {
              super(props)
              this.books = [
                { name: 'Harry Potter' },
                { name: 'Net Moves' },
                { name: 'Half of a yellow sun' },
                { name: 'The Da Vinci Code' },
                { name: 'Born a crime' },
              ];
      
              this.state = {
                // currently selected dropdown item
                selectedBook: ''
              }
      
              this.onChange = this.onChange.bind(this)
            }
      
            onChange(selectedBook) {
              this.setState({ selectedBook: selectedBook.name })
            }
      
            render() {
              return (
                <Downshift onChange={this.onChange} selectedItem={this.state.selectedBook} itemToString={books => (books ? books.name : '')}>
                // pass the downshift props into a callback
                  {({ isOpen, getToggleButtonProps, getItemProps, highlightedIndex, selectedItem: dsSelectedItem, getLabelProps }) => (
                    <div>
                      // add a label tag and pass our label text to the getLabelProps function
                      <label style={{ marginTop: '1rem', display: 'block' }} {...getLabelProps()}>Select your favourite book</label> <br />
                      // add a button for our dropdown and pass the selected book as its content if there's a selected item
                      <button className="dropdown-button" {...getToggleButtonProps()}>
                        {this.state.selectedBook !== '' ? this.state.selectedBook : 'Select a book ...'}
                      </button>
                      <div style={{ position: 'relative' }}>
                        // if the input element is open, render the div else render nothing
                        {isOpen ? (
                          <div className="downshift-dropdown">
                            {
                              // map through all the books and render them
                              this.books.map((item, index) => (
                                <div
                                  className="dropdown-item"
                                  {...getItemProps({ key: index, index, item })}
                                  style={{
                                    backgroundColor: highlightedIndex === index ? 'lightgray' : 'white',
                                    fontWeight: dsSelectedItem === item ? 'bold' : 'normal',
                                  }}>
                                  {item.name}
                                </div>
                              ))
                            }
                          </div>
                        ) : null}
                      </div>
                    </div>
                  )}
                </Downshift>
              )
            }
          }
      

      In the code above, we have a DownshiftThree class component where we render the <Downshift/> component. In the callback passed to it, we have a button where we pass the getToggleButtonProps function. The button houses a ternary operator where we set the content the button based on whether the selectedBook in the component’s state is set.

      Next, we call the isOpen prop to see if the dropdown is open or not. If it is open, we map through all the books and render them in the dropdown.

      In the onChange method passed to the <Downshift/> component, whenever an item is selected, we set it the state, thereby updating the content of the button.
      Import and render the component to the parent App component and reload your browser to see the app at this point.

      Step 5 — Creating Forms with Downshift

      In this example, we’ll be using a Downshift input component as input fields in a form and attempting to submit the form data. In the src directory, let’s create two files: DownshiftInputField.js and DownshiftFour.js.

      In the DownshiftInputField.js, we’ll create an input component with Downshift and use it to render some input fields in the DownshiftFour.js file. Let’s create a functional component in our DownshiftInputField.js file:

      src/DownshiftInputField.js

          import React from 'react'
          import Downshift from 'downshift';
      
          export default ({ items, onChange, label, placeholder, name }) => {
            return (
              <Downshift onChange={onChange} itemToString={items => (items ? items.name : '')}>
                {({ getInputProps, getItemProps, isOpen, inputValue, highlightedIndex, selectedItem, getLabelProps }) => (
                  <div>
                  // add a label tag and pass our label text to the getLabelProps function
                    <label style={{ marginTop: '1rem', display: 'block' }} {...getLabelProps()}>{label}</label> <br />
                    // add an input tag and pass our placeholder text to the getInputProps function
                    <input name={name} {...getInputProps({ placeholder })} />
                    // if the input element is open, render the div else render nothing
                    {isOpen ? (
                      <div className="downshift-dropdown">
                        {
                          items
                            // filter the items and return those that includes the inputValue
                            .filter(item => !inputValue || item.name.toLowerCase().includes(inputValue.toLowerCase()))
                            // map through the returned items and render them to the page
                            .map((item, index) => (
                              <div
                                className="dropdown-item"
                                {...getItemProps({ key: item.name, index, item })}
                                style={{
                                  backgroundColor: highlightedIndex === index ? 'lightgray' : 'white',
                                  fontWeight: selectedItem === item ? 'bold' : 'normal',
                                }}>
                                {item.name}
                              </div>
                            ))
                        }
                      </div>
                    ) : null}
                  </div>
                )}
              </Downshift>
            )
          }
      

      In the code above, our functional component takes in an array of items, an onChange function, a label and placeholder text, and finally a name. The component returns a <Downshift/> component which receives all the required props in a callback function. In the callback, we have a label and an input field.

      As with other examples, we pass the isOpen prop to a ternary operator. If the input field is open, we filter through the array of items to return items that match the inputValue, then we map through the returned items and render them to the DOM.

      Now that our input field component is ready, let’s import it into the DownshiftFour.js file:

      src/DownshiftFour.js

          import React, { Component } from 'react'
          import DownshiftInputField from './DownshiftInputField';
      
          export default class DownshiftFour extends Component {
            constructor(props) {
              super(props)
              this.state = {
                books: [
                  { name: 'Harry Potter' },
                  { name: 'Net Moves' },
                  { name: 'Half of a yellow sun' },
                  { name: 'The Da Vinci Code' },
                  { name: 'Born a crime' },
                ],
                movies: [
                  { name: 'Harry Potter' },
                  { name: '12 Strong' },
                  { name: 'Half of a yellow sun' },
                  { name: 'Gringo' },
                  { name: 'Black Panther' },
                ],
                book: '',
                movie: ''
              }
              this.onSubmit = this.onSubmit.bind(this);
              this.onChange = this.onChange.bind(this);
            }
      
            onSubmit(event) {
              event.preventDefault();
              alert(`
              Favourite book: ${this.state.book}
              Favourite movie: ${this.state.movie}
              has been submitted
              `)
            }
      
            onChange(selectedBook, stateAndHelpers) {
              const element = document.querySelector(`#${stateAndHelpers.id}-input`)
              this.setState({ [element.name]: selectedBook.name })
            }
      
            render() {
              return (
                <form onSubmit={this.onSubmit}>
                  <DownshiftInputField
                    items={this.state.books}
                    onChange={this.onChange}
                    label="Select your favourite book"
                    name="book"
                    placeholder="Search your favourite book" />
                  <DownshiftInputField
                    items={this.state.movies}
                    onChange={this.onChange}
                    label="Select your favourite movie"
                    name="movie"
                    placeholder="Search your favourite movie" />
                  <input type="submit" value="Submit" className="dropdown-button" />
                </form>
              )
            }
          }
      

      In our DownshiftFour.js file, we imported our input field component and created a class component. In our component state, we have an array of books and movies and we render our input field component twice in a form: one as an input field for books and another for movies.

      Downshift’s onChange function takes in a second parameter called stateAndHelpers which gives us some information about Downshift’s current state.

      In the onChange method, we find the input field the user is currently interacting with by getting it’s id from the stateAndHelpers argument and querying the DOM for it. Once we have the element, we set it to the component state.

      When the user hits the submit button, the onSubmit method, gets the selected book and movie from the state and does whatever we want with it.

      Import and render the <DownshiftFour/> component in the parent App component and let’s give it a spin in the browser.

      Step 6 — Using Downshift with Popper.js

      In our last example for this article, we’ll be using Popper.js to change the directions of a Downshift popup. Popper is a library that makes positioning tooltips or popups a more manageable task.

      We already installed the react-popper package while setting up the application, so let’s create a DownshiftFive.js file in the src folder.

      Let’s add the following code to the new file:

      src/DownshiftFive.js

          import React, { Component } from 'react'
          import Downshift from 'downshift';
          import { Popper, Manager, Target } from 'react-popper';
      
          export default class DownshiftFive extends Component {
            // define some default props
            static defaultProps = {
              positions: [
                'top',
                'top-start',
                'top-end',
                'bottom-start',
                'bottom',
                'bottom-end',
              ]
            }
      
            render() {
              return (
                <div className="popper-div">
                // wrap the whole component in Popper's <Manager/> component
                  <Manager>
                    <Downshift render={({ inputValue, getInputProps, getItemProps, isOpen, selectedItem, highlightedIndex }) => (
                      <div>
                      // wrap our input element in Popper's <Target/> component
                        <Target>
                          <input {...getInputProps({ placeholder: 'Enter a position' })} />
                        </Target>
                        <div className="downshift-dropdown">
                          {isOpen ? (
                          // pass the selected item to Popper
                            <Popper
                              placement={selectedItem || 'bottom'}
                              style={{ backgroundColor: 'skyblue' }}
                            >
                              {
                              // filter through all the positions and return the ones that include the inputValue
                                this.props.positions
                                  .filter(item => !inputValue || item.includes(inputValue.toLowerCase()))
                                  // map through all the returned positions and render them
                                  .map((item, index) => (
                                    <div className="downshift-item popper-item"
                                      {...getItemProps({ item })}
                                      key={item}
                                      style={{
                                        cursor: 'pointer',
                                        backgroundColor: highlightedIndex === index ? '#bed5df' : 'transparent',
                                        fontWeight: selectedItem === item ? 'bold' : 'normal',
                                      }}>
                                      {item}
                                    </div>
                                  ))
                              }
                            </Popper>
                          ) : null}
                        </div>
                      </div>
                    )}></Downshift>
                  </Manager>
                </div>
              )
            }
          }
      

      In the code snippet above, we create a DownshiftFive class components with a default position props. These are the positions Popper will use to render our popup. In the render method of the component, we’re returning a <Downshift/> component wrapped in a <Manager/> component:

          return (
            <div className="popper-div">
              <Manager>
                <Downshift render={({ inputValue, getInputProps, getItemProps, isOpen, selectedItem, highlightedIndex }) => (
                  {/* all of our remaining code goes here */}
                )}>
                </DownShift>
              </Manager>
            </div>
          )
      

      The Manager component is a wrapper exposed by Popper that needs to surround all other react-popper components on the page to make them communicate with each other.

      If you look closely, you’ll see we’re passing a render prop to the <Downshift/> component. This is another way to pass our props to the <Downshift/> component. Basically, we moved our callback and passed it to the render prop.

      In the callback passed to the render prop, we wrap our input field in a <Target/> component. This informs Popper that this is the input field around which the popup should be rendered.

      Next, we check if our input is open and render a <Popper/> component and pass our selectedItem to its placement prop. This helps Popper reposition the popup whenever a new position is selected. Lastly, as with other examples, we filter all the default prop positions, return the positions that include the inputValue, map through them and render them on the page.

      Finally, import and render the <DownshiftFive/> component in the parent App component and check it out in the browser. You will see the final product.

      Conclusion

      In this post, you’ve created an application to explore common React dropdown use cases solved with Downshift.



      Source link

      Common Linode StackScripts Use Cases


      Updated by Linode

      Contributed by
      Linode

      What are StackScripts?

      StackScripts provide Linode users with the ability to automate the deployment of custom systems on top of Linode’s default Linux distribution images. For example, every time you deploy a new Linode you might execute the same tasks, like updating your system’s software, installing your favorite Linux tools, and adding a limited user account. These tasks can be automated using a StackScript that will perform these actions for you as part of your Linode’s first boot process.

      All StackScripts are stored in the Linode Cloud Manager and can be accessed whenever you deploy a Linode. A StackScript authored by you is an Account StackScript. A Community StackScript is a StackScript created by a Linode community member that has made their StackScript publicly available in the Linode Cloud Manager.

      StackScript Use Cases

      Automating Common System Administration Tasks

      Whenever you deploy a new Linode, there are basic system administration tasks that you must perform, like installing system software updates, setting your Linode’s hostname, setting the timezone, and securing your server. You can create a StackScript to automate all these steps and use it each time you deploy a new Linode. There are few limitations to what you can automate using a StackScript, because its underlying mechanism works just like any script you might execute on a Linux system. StackScripts ensure that each Linode you deploy is configured exactly to your preferences each time.

      Since you can make any StackScript public to the Linode Community, your entire team can use the StackScripts you create to easily deploy base identical systems.

      Demonstrating your Software

      If you develop software, you can use StackScripts to deploy a demonstration instance of your software. The resulting system may not need to be particularly durable or be fully configured, since you can redeploy a new Linode exactly as written in your StackScript. This is an easy and reproducible way to spin up quick demos of your software.

      Distributing your Software

      Community StackScripts are publicly available to the entire Linode Community. This means if you have an open source project you’d like to make easily available to Linode users, you can write a StackScript that installs and configures your project’s software on a Linode. Include user defined variables in your StackScript to make it customizable to users during each deployment of the StackScript.

      Note

      If you would also like to make your open source project available to the Linode Community as an App in the Linode Marketplace, see the Linode One-Click App Marketplace page for details.

      Deploy Cluster Instances

      If your application makes use of a cluster of nodes, you may be able to automate the deployment of a new cluster-member by using StackScripts to configure the instance. StackScripts, in combination with the Linode API, can help you to elastically automate deployment and management of a cluster’s node. Similarly, you can apply the same concept to creating a server appliance instance.

      Next Steps

      To get started creating your first StackScript, see the A Tutorial for Creating and Managing StackScripts.

      This guide is published under a CC BY-ND 4.0 license.



      Source link