One place for hosting & domains

      Create

      Create and Manage StackScripts – A Tutorial


      Updated by Linode

      Written 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. While a Community StackScript is a StackScript created by a Linode community member that has made their StackScript publicly available in the Linode Cloud Manager.

      In this Guide

      This guide will show you how to do the following:

      Note

      Create a New StackScript

      1. Log into the Linode Cloud Manager.

      2. Click on the StackScripts link in the left-hand navigation menu. You will be brought to the StackScripts page.

        Click on the StackScripts link in the left-hand navigation menu.

      3. Viewing the Account StackScripts section, click on the Create New StackScript link at the top of the page.

        Click on the Create New StackScript link.

      4. On the Create New StackScript page, provide the required configurations to create your StackScript.

        Field Description
        StackScript Label The name with which to identify your StackScript. Required.
        Description An overview of what your StackScript does.
        Target Images The Linux distributions that can run this StackScript. Required.
        Script The body of the script. See the Writing Scripts for Use with Linode StackScripts section for more details. Required.
        Revision Note A short description of the updates made to your StackScript in this version of your script.



        Example Script

        The file below displays an example of a simple script that executes some basic set up steps on a Linode. Review the example’s comments for details on what each line of the script does.

        Example Script
         1
         2
         3
         4
         5
         6
         7
         8
         9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        24
        
        #!/bin/bash
        # This block defines the variables the user of the script needs to provide
        # when deploying using this script.
        #
        #
        #<UDF name="hostname" label="The hostname for the new Linode.">
        # HOSTNAME=
        #
        #<UDF name="fqdn" label="The new Linode's Fully Qualified Domain Name">
        # FQDN=
        
        # This sets the variable $IPADDR to the IP address the new Linode receives.
        IPADDR=$(/sbin/ifconfig eth0 | awk '/inet / { print $2 }' | sed 's/addr://')
        
        # This updates the packages on the system from the distribution repositories.
        apt-get update
        apt-get upgrade -y
        
        # This section sets the hostname.
        echo $HOSTNAME > /etc/hostname
        hostname -F /etc/hostname
        
        # This section sets the Fully Qualified Domain Name (FQDN) in the hosts file.
        echo $IPADDR $FQDN $HOSTNAME >> /etc/hosts
      5. Click Save when you are done. You can always edit your script later if needed. You will be brought back to the StackScripts page, where your new StackScript will be visible and ready to use with a new Linode deployment.

        Note

        View your new StackScript on the StackScripts page.

      Manage StackScripts

      Edit an Account StackScript

      After you’ve created an Account StackScript, you can go back and edit it as required. This section will show you how to access a StackScript for editing.

      1. Log into the Linode Cloud Manager.

      2. Click on the StackScripts link in the left-hand navigation menu. You will be brought to the StackScripts page.

        Click on the StackScripts link in the left-hand navigation menu.

      3. Viewing the Account StackScripts tab, you will see a list of all of your account’s StackScripts. This will include both private and public StackScripts. Click on the more options ellipsis corresponding to the StackScript you’d like to modify and select Edit from the dropdown menu.

        Select **Edit** from the dropdown menu to edit your StackScript.

      4. On your StackScript’s Edit page, modify it as needed and click Save to keep your changes.

      Make an Account StackScript Public

      You can make any of your Account StackScripts public. When an account StackScript is public it will become available to the rest of the Linode Community in the Cloud Manager as a Community StackScript.

      Caution

      Once you make an Account StackScript public, you will not be able to make it private again or to delete it. You can, however, edit your public StackScript, if needed.

      1. Log into the Linode Cloud Manager.

      2. Click on the StackScripts link in the left-hand navigation menu. You will be brought to the StackScripts page.

        Click on the StackScripts link in the left-hand navigation menu.

      3. Viewing the Account StackScripts tab, you will see a list of all of your account’s StackScripts. This will include both private and public StackScripts. Click on the more options ellipsis corresponding to the StackScript you’d like to make public and select Make StackScript Public from the dropdown menu.

        Select Make StackScript Public from the dropdown menu.

        A dialog box will appear asking you to confirm the action. Click on Yes, make me a star! if you would like to proceed. You will be brought back to the Account StackScripts page.

        Note

      Delete an Account StackScript

      Note

      You cannot delete Account StackScripts that have been made public.
      1. Click on the StackScripts link in the left-hand navigation menu. You will be brought to the StackScripts page.

        Click on the StackScripts link in the left-hand navigation menu.

      2. Viewing the Account StackScripts tab, you will see a list of all of your account’s StackScripts. Click on the more options ellipsis corresponding to the StackScript you’d like to delete and select Delete from the dropdown menu.

        Select Make StackScript Public from the dropdown menu.

        A dialog box will appear asking you to confirm the action. Click on Delete if you would like to proceed.

      Next Steps

      Now that you have created a StackScript, you can deploy a Linode using your StackScript. See the Deploying a New Linode Using a StackScript guide for details.

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



      Source link

      How To Create Wrapper Components in React with Props


      The author selected Creative Commons to receive a donation as part of the Write for DOnations program.

      Introduction

      In this tutorial, you’ll create wrapper components with props using the React JavaScript library. Wrapper components are components that surround unknown components and provide a default structure to display the child components. This pattern is useful for creating user interface (UI) elements that are used repeatedly throughout a design, like modals, template pages, and information tiles.

      To create wrapper components, you’ll first learn to use the rest and spread operators to collect unused props to pass down to nested components. Then you’ll create a component that uses the built-in children component to wrap nested components in JSX as if they were HTML elements. Finally, you’ll pass components as props to create flexible wrappers that can embed custom JSX in multiple locations in a component.

      During the tutorial, you’ll build components to display a list of animal data in the form of cards. You’ll learn to split data and refactor components as you create flexible wrapping components. By the end of this tutorial, you’ll have a working application that will use advanced prop techniques to create reusable components that will scale and adapt as you application grows and changes.

      Note: The first step sets up a blank project on which you will build the tutorial exercise. If you already have a working project and want to go directly to working with props, start with Step 2.

      Prerequisites

      Step 1 — Creating an Empty Project

      In this step, you’ll create a new project using Create React App. Then you will delete the sample project and related files that are installed when you bootstrap the project. Finally, you will create a simple file structure to organize your components. This will give you a solid basis on which to build this tutorial’s wrapper application in the next step.

      To start, make a new project. In your command line, run the following script to install a fresh project using create-react-app:

      • npx create-react-app wrapper-tutorial

      After the project is finished, change into the directory:

      In a new terminal tab or window, start the project using the Create React App start script. The browser will auto-refresh on changes, so leave this script running while you work:

      You will get a running local server. If the project did not open in a browser window, you can open it with http://localhost:3000/. If you are running this from a remote server, the address will be http://your_domain:3000.

      Your browser will load with a simple React application included as part of Create React App:

      React template project

      You will be building a completely new set of custom components, so you’ll need to start by clearing out some boilerplate code so that you can have an empty project.

      To start, open src/App.js in a text editor. This is the root component that is injected into the page. All components will start from here. You can find more information about App.js at How To Set Up a React Project with Create React App.

      Open src/App.js with the following command:

      You will see a file like this:

      wrapper-tutorial/src/App.js

      import React from 'react';
      import logo from './logo.svg';
      import './App.css';
      
      function App() {
        return (
          <div className="App">
            <header className="App-header">
              <img src={logo} className="App-logo" alt="logo" />
              <p>
                Edit <code>src/App.js</code> and save to reload.
              </p>
              <a
                className="App-link"
                href="https://reactjs.org"
                target="_blank"
                rel="noopener noreferrer"
              >
                Learn React
              </a>
            </header>
          </div>
        );
      }
      
      export default App;
      

      Delete the line import logo from './logo.svg';. Then replace everything in the return statement to return a set of empty tags: <></>. This will give you a valid page that returns nothing. The final code will look like this:

      wrapper-tutorial/src/App.js

      
      import React from 'react';
      import './App.css';
      
      function App() {
        return <></>;
      }
      
      export default App;
      

      Save and exit the text editor.

      Finally, delete the logo. You won’t be using it in your application and you should remove unused files as you work. It will save you from confusion in the long run.

      In the terminal window type the following command:

      If you look at your browser, you will see a blank screen.

      blank screen in chrome

      Now that you have cleared out the sample Create React App project, create a simple file structure. This will help you keep your components isolated and independent.

      Create a directory called components in the src directory. This will hold all of you custom components.

      Each component will have its own directory to store the component file along with the styles, images if there are any, and tests.

      Create a directory for App:

      Move all of the App files into that directory. Use the wildcard, *, to select any files that start with App. regardless of file extension. Then use the mv command to put them into the new directory:

      • mv src/App.* src/components/App

      Next, update the relative import path in index.js, which is the root component that bootstraps the whole process:

      The import statement needs to point to the App.js file in the App directory, so make the following highlighted change:

      wrapper-tutorial/src/index.js

      import React from 'react';
      import ReactDOM from 'react-dom';
      import './index.css';
      import App from './components/App/App';
      import * as serviceWorker from './serviceWorker';
      
      ReactDOM.render(
        <React.StrictMode>
          <App />
        </React.StrictMode>,
        document.getElementById('root')
      );
      
      // If you want your app to work offline and load faster, you can change
      // unregister() to register() below. Note this comes with some pitfalls.
      // Learn more about service workers: https://bit.ly/CRA-PWA
      serviceWorker.unregister();
      

      Save and exit the file.

      Now that the project is set up, you can create your first component.

      Step 2 — Collecting Unused Props with ...props

      In this step, you’ll create a component to display a set of data about a group of animals. Your component will contain a second nested component to display some information visually. To connect the parent and nested component, you’ll use the rest and spread operators to pass unused props from the parent to the child without the parent needing to be aware of the names or types of the props.

      By the end of this step, you’ll have a parent component that can provide props to nested components without having to know what the props are. This will keep the parent component flexible, allowing you to update the child component without having to change the parent.

      Creating an AnimalCard Component

      To start, create a set of data for your animals. First, open a file containing the data set in the components/App directory:

      • nano src/components/App/data.js

      Add the following data:

      src/components/App/data.js

      
      export default [
        {
          name: 'Lion',
          scientificName: 'Panthero leo',
          size: 140,
          diet: ['meat']
        },
        {
          name: 'Gorilla',
          scientificName: 'Gorilla beringei',
          size: 205,
          diet: ['plants', 'insects']
        },
        {
          name: 'Zebra',
          scientificName: 'Equus quagga',
          size: 322,
          diet: ['plants'],
        }
      ]
      

      This list of animals is an array of objects that includes the animal’s name, scientific name, weight, and diet.

      Save and close the file.

      Next, create a directory for the AnimalCard component:

      • mkdir src/components/AnimalCard

      Open a new file in the directo:

      • nano src/components/AnimalCard/AnimalCard.js

      Now add a component that will take the name, diet, and size as a prop and display it:

      wrapper-tutorial/src/components/AnimalCard/AnimalCard.js

      import React from 'react';
      import PropTypes from 'prop-types';
      
      export default function AnimalCard({ diet, name, size }) {
        return(
          <div>
            <h3>{name}</h3>
            <div>{size}kg</div>
            <div>{diet.join(', ')}.</div>
          </div>
        )
      }
      
      AnimalCard.propTypes = {
        diet: PropTypes.arrayOf(PropTypes.string).isRequired,
        name: PropTypes.string.isRequired,
        size: PropTypes.number.isRequired,
      }
      

      Here you are destructuring the props in the parameter list for the AnimalCard function, then displaying the data in a div. The diet data is listed as a single string using the join() method. Each piece of data includes a corresponding PropType to make sure the data type is correct.

      Save and close the file.

      Now that you have your component and your data, you need to combine them together. To do that, import the component and the data into the root component of your project: App.js.

      First, open the component:

      • nano src/components/App/App.js

      From there, you can loop over the data and return a new AnimalCard with the relevant props. Add the highlighted lines to App.js:

      wrapper-tutorial/src/components/App/App.js

      import React from 'react';
      import './App.css';
      
      import animals from './data';
      import AnimalCard from '../AnimalCard/AnimalCard';
      
      function App() {
        return (
          <div className="wrapper">
            {animals.map(animal =>
              <AnimalCard
                diet={animal.diet}
                key={animal.name}
                name={animal.name}
                size={animal.size}
              />
            )}
          </div>
        );
      }
      
      export default App;
      

      Save and close the file.

      As you work on more complex projects, your data will come from more varied places, such as APIs, localStorage, or static files. But the process for using each of these will be similar: assign the data to a variable and loop over the data. In this case, the data is from a static file, so you are importing directly to a variable.

      In this code, you use the .map() method to iterate over animals and display the props. Notice that you do not have to use every piece of data. You are not explicitly passing the scientificName property, for example. You are also adding a separate key prop that React will use to keep track of the mapped data. Finally, you are wrapping the code with a div with a className of wrapper that you’ll use to add some styling.

      To add this styling, open App.css:

      • nano src/components/App/App.css

      Remove the boilerplate styling and add flex properties to a class called wrapper:

      prop-tutorial/src/components/App/App.js

      .wrapper {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          padding: 20px;
      }
      

      This will use flexbox layout to organize the data so it will line up. padding gives some space in the browser window, and justify-content spreads out the extra space between elements.

      Save and exit the file. When you do, the browser will refresh and you’ll see some data spaced out.

      Browser with data spaced out

      Creating a Details Component

      You now have a simple component that displays the data. But let’s say you wanted to give the diet data a little flair by converting the text to an emoji. You can do this by converting the data in your component.

      React is designed to be flexible, so when you are thinking about how to convert data, you have a few different options:

      • You can create a function inside the component that converts the text to an emoji.
      • You can create a function and store it in a file outside the component so that you can reuse the logic across different components.
      • You can create a separate component that converts the text to an emoji.

      Each approach is fine when applied to the right use case, and you’ll find yourself switching between them as you build an application. To avoid premature abstraction and complexity, you should use the first option to start. If you find yourself wanting to reuse logic, you can pull the function out separately from the component. The third option is best if you want to have a reusable piece that includes the logic and the markup, or that you want to isolate to use across the application.

      In this case, we’ll make a new component, since we will want to add more data later and we are combining markup with conversion logic.

      The new component will be called AnimalDetails. To make it, create a new directory:

      • mkdir src/components/AnimalDetails

      Next, open AnimalDetails.js in your text editor:

      • nano src/components/AnimalDetails/AnimalDetails.js

      Inside the file, make a small component that displays the diet as an emoji:

      wrapper-tutorial/src/components/AnimalDetails/AnimalDetails.js

      import React from 'react';
      import PropTypes from 'prop-types';
      import './AnimalDetails.css';
      
      function convertFood(food) {
        switch(food) {
          case 'insects':
            return '🐜';
          case 'meat':
            return '🍖';
          case 'plants':
          default:
            return '🌱';
        }
      }
      
      export default function AnimalDetails({ diet }) {
        return(
          <div className="details">
            <h4>Details:</h4>
            <div>
              Diet: {diet.map(food => convertFood(food)).join(' ')}
            </div>
          </div>
        )
      }
      
      AnimalDetails.propTypes = {
        diet: PropTypes.arrayOf(PropTypes.string).isRequired,
      }
      

      The AnimalDetails.propTypes object sets up the function to take a prop of diet that is an array of strings. Then inside the component, the code loops over the diet and converts the string to an emoji using the switch statement.

      Save and close the file.

      You are also importing some CSS, so let’s add that now.

      Open AnimalDetails.css:

      • nano src/components/AnimalDetails/AnimalDetails.css

      Add some CSS to give the element a border and margin to separate the details from the rest of the component:

      wrapper-tutorial/src/components/AnimalDetails/AnimalDetails.css

      .details {
          border-top: gray solid 1px;
          margin: 20px 0;
      }
      

      We use .details to match the rule to elements with a className of details.

      Save and close the file.

      Now that you have a new custom component, you can add it to your AnimalCard component. Open AnimalCard.js:

      • nano src/components/AnimalCard/AnimalCard.js

      Replace the diet.join statement with the new AnimalDetails component and pass diet as a prop by adding the highlighted lines:

      wrapper-tutorial/src/components/AnimalCard/AnimalCard.js

      import React from 'react';
      import PropTypes from 'prop-types';
      import AnimalDetails from '../AnimalDetails/AnimalDetails';
      
      export default function AnimalCard({ diet, name, size }) {
        return(
          <div>
            <h3>{name}</h3>
            <div>{size}kg</div>
            <AnimalDetails
              diet={diet}
            />
          </div>
        )
      }
      
      AnimalCard.propTypes = {
        diet: PropTypes.arrayOf(PropTypes.string).isRequired,
        name: PropTypes.string.isRequired,
        size: PropTypes.number.isRequired,
      }
      

      Save the file and you’ll see the new details in the browser.

      Browser with details

      Passing Details Through a Component with ...props

      The components are working well together, but there’s a slight inefficiency in AnimalCard. You are explicitly pulling diet out from the props argument, but you aren’t using the data. Instead, you are passing it through to the component. There’s nothing inherently wrong about this—in fact, it’s often better to err on the side of too much communication. But in doing this, you make your code more difficult to maintain. Whenever you want to pass new data to AnimalDetails, you need to update three places: App, where you pass the props, AnimalDetails, which consumes the prop, and AnimalCard, which is the go-between.

      A better way is to gather any unused props inside AnimalCard and then pass those directly to AnimalDetails. This gives you the chance to make changes to AnimalDetails without changing AnimalCard. In effect, AnimalCard doesn’t need to know anything about the props or the PropTypes that are going into AnimalDetails.

      To do that, you’ll use the object rest operator. This operator collects any items that are not pulled out during destructuring and saves them into a new object.

      Here’s a simple example:

      const dog = {
          name: 'dog',
          diet: ['meat']
      }
      
      const { name, ...props  } = dog;
      

      In this case, the variable name will be 'dog' and the variable props will be { diet: ['meat']}.

      Up till now, you’ve passed all props as if they were HTML attributes, but you can also use objects to send props. To use an object as a prop, you need to use the spread operator—...props—surrounded with curly braces. This will change each key-value pair into a prop.

      Open AnimalCard.js:

      • nano src/components/AnimalCard/AnimalCard.js

      Inside, remove diet from the destructured object and instead collect the rest of the props into a variable called props. Then pass those props directly to AnimalDetails:

      wrapper-tutorial/src/components/AnimalCard/AnimalCard.js

      import React from 'react';
      import PropTypes from 'prop-types';
      import AnimalDetails from '../AnimalDetails/AnimalDetails';
      
      export default function AnimalCard({ name, size, ...props }) {
        return(
          <div>
            <h3>{name}</h3>
            <div>{size}kg</div>
            <AnimalDetails
              {...props}
            />
          </div>
        )
      }
      
      AnimalCard.propTypes = {
        name: PropTypes.string.isRequired,
        size: PropTypes.number.isRequired,
      }
      

      Notice that you can remove the diet PropType since you are not using the prop in this component.

      In this case, you are only passing one prop to AnimalDetails. In cases where you have multiple props, the order will matter. A later prop will overwrite earlier props, so if you have a prop you want to take priority, make sure it is last. This can cause some confusion if your props object has a property that is also a named value.

      Save and close the file. The browser will refresh and everything will look the same:

      Browser with details

      To see how the ...props object adds flexibility, let’s pass the scientificName to AnimalDetails via the AnimalCard component.

      First, open App.js:

      • nano src/components/App/App.js

      Then pass the scientificName as a prop:

      wrapper-tutorial/src/components/App/App.js

      import React from 'react';
      import './App.css';
      
      import animals from './data';
      import AnimalCard from '../AnimalCard/AnimalCard';
      
      function App() {
        return (
          <div className="wrapper">
            {animals.map(animal =>
              <AnimalCard
                diet={animal.diet}
                key={animal.name}
                name={animal.name}
                size={animal.size}
                scientificName={animal.scientificName}
              />
            )}
          </div>
        );
      }
      
      export default App;
      

      Save and close the file.

      Skip over AnimalCard; you won’t need to make any changes there. Then open AnimalDetails so you can consume the new prop:

      • nano src/components/AnimalDetails/AnimalDetails.js

      The new prop will be a string, which you’ll add to the details list along with a line declaring the PropType:

      wrapper-tutorial/src/components/AnimalDetails/AnimalDetails.js

      import React from 'react';
      ...
      export default function AnimalDetails({ diet, scientificName }) {
        return(
          <div className="details">
            <h4>Details:</h4>
            <div>
              Scientific Name: {scientificName}.
            </div>
            <div>
              Diet: {diet.map(food => convertFood(food)).join(' ')}
            </div>
          </div>
        )
      }
      
      AnimalDetails.propTypes = {
        diet: PropTypes.arrayOf(PropTypes.string).isRequired,
        scientificName: PropTypes.string.isRequired,
      }
      

      Save and close the file. When you do, the browser will refresh and you’ll see the new details without any changes to the AnimalCard component:

      Browser with scientific name

      In this step, you learned how to create flexible parent props that can take unknown props and pass them into nested components with the spread operator. This is a common pattern that will give you the flexibility you need to create components with focused responsibilities. In the next step, you’ll create components that can take unknown components as a prop using the built in children prop.

      Step 3 — Creating Wrapper Components with children

      In this step, you’ll create a wrapper component that can take an unknown group of components as a prop. This will give you the ability to nest components like standard HTML, and it will give you a pattern for creating reusable wrappers that will let you make a variety of components that need a common design but a flexible interior.

      React gives you a built-in prop called children that collects any children components. Using this makes creating wrapper components intuitivie and readable.

      To start, make a new component called Card. This will be a wrapper component to create a standard style for any new card components.

      Create a new directory:

      • mkdir src/components/Card

      Then open the Card component in your text editor:

      • nano src/components/Card/Card.js

      Create a component that takes children and title as props and wraps them in a div by adding the following code:

      wrapper-tutorial/src/components/Card/Card.js

      import React from 'react';
      import PropTypes from 'prop-types';
      import './Card.css';
      
      export default function Card({ children, title }) {
        return(
          <div className="card">
            <div className="card-details">
              <h2>{title}</h2>
            </div>
            {children}
          </div>
        )
      }
      
      Card.propTypes = {
        children: PropTypes.oneOfType([
          PropTypes.arrayOf(PropTypes.element), 
          PropTypes.element.isRequired
        ]),
        title: PropTypes.string.isRequired,
      }
      

      The PropTypes for the children are new. The children prop can either be a JSX element or an array of JSX elements. The title is a string.

      Save and close the file.

      Next, add some styling. Open Card.css:

      • nano src/components/Card/Card.css

      Your card will have a border and a line under the details.

      wrapper-tutorial/src/components/Card/Card.css

      .card {
          border: black solid 1px;
          margin: 10px;
          padding: 10px;
          width: 200px;
      }
      
      .card-details {
          border-bottom: gray solid 1px;
          margin-bottom: 20px;
      }
      

      Save and close the file. Now that you have your component you need to use it. You could wrap each AnimalCard with the Card component in App.js, but since the name AnimalCard implies it is already a Card, it would be better to use the Card component inside of AnimalCard.

      Open up AnimalCard:

      • nano src/components/AnimalCard/AnimalCard.js

      Unlike other props, you don’t pass children explicitly. Instead, you include the JSX as if they were HTML child elements. In other words, you just nest them inside of the element, like the following:

      wrapper-tutorial/src/components/AnimalCard/AnimalCard.js

      import React from 'react';
      import PropTypes from 'prop-types';
      import Card from '../Card/Card';
      import AnimalDetails from '../AnimalDetails/AnimalDetails';
      
      export default function AnimalCard({ name, size, ...props }) {
        return(
          <Card title="Animal">
            <h3>{name}</h3>
            <div>{size}kg</div>
            <AnimalDetails
              {...props}
            />
          </Card>
        )
      }
      
      AnimalCard.propTypes = {
        name: PropTypes.string.isRequired,
        size: PropTypes.number.isRequired,
      }
      

      Unlike a React component, you do not need to have a single root element as a child. That’s why the PropType for Card specified it could be an array of elements or a single element. In addition to passing the children as nested components, you are giving the card a title of Animal.

      Save and close the file. When you do, the browser will refresh and you’ll see the updated card component.

      Browser with cards

      Now you have a reusable Card component that can take any number of nested children. The primary advantage of this is that you can reuse the Card with any arbitrary component. If you wanted to make a Plant card, you could do that by wrapping the plant information with the Card component. It doesn’t even need to relate at all: If you wanted to reuse the Card component in a completely different applications that lists things like music or account data, you could do that, too. The Card component doesn’t care what the children are; you are just reusing the wrapper element, which in this case is the styled border and title.

      The downside to using children is that you can only have one instance of the child prop. Occasionally, you’ll want a component to have custom JSX in multiple places. Fortunately, you can do that by passing JSX and React components as props, which we will cover in the next step.

      Step 4 — Passing Components as Props

      In this step, you’ll modify your Card component to take other components as props. This will give your component maximum flexibility to display unknown components or JSX in multiple locations throughout the page. Unlike children, which you can only use once, you can have as many components as props, giving your wrapper component the ability to adapt to a variety of needs while maintaining a standard look and structure.

      By the end of this step, you’ll have a component that can wrap children components and also display other components in the card. This pattern will give you flexibility when you need to create components that need information that is more complex than simple strings and integers.

      Let’s modify the Card component to take an arbitrary React element called details.

      First, open the Card component:

      • nano src/components/Card/Card.js

      Next, add a new prop called details and place it below the <h2> element:

      wrapper-tutorial/src/components/Card/Card.js

      import React from 'react';
      import PropTypes from 'prop-types';
      import './Card.css';
      
      export default function Card({ children, details, title }) {
        return(
          <div className="card">
            <div className="card-details">
              <h2>{title}</h2>
              {details}
            </div>
            {children}
          </div>
        )
      }
      
      Card.propTypes = {
        children: PropTypes.oneOfType([
          PropTypes.arrayOf(PropTypes.element), 
          PropTypes.element.isRequired
        ]),
        details: PropTypes.element,
        title: PropTypes.string.isRequired,
      }
      
      Card.defaultProps = {
        details: null,
      }
      

      This prop will have the same type as children, but it should be optional. To make it optional, you add a default value of null. In this case, if a user passes no details, the component will still be valid and will not display anything extra.

      Save and close the file. The page will refresh and you’ll see the same image as before:

      Browser with cards

      Now add some details to the AnimalCard. First, open AnimalCard.

      • nano src/components/AnimalCard/AnimalCard.js

      Since the Card component is already using children, you’ll need to pass the new JSX component as a prop. Since these are all mammals, add that to the card, but wrap it in <em> tags to make it italic.

      wrapper-tutorial/src/components/AnimalCard/AnimalCard.js

      import React from 'react';
      ...
      
      export default function AnimalCard({ name, size, ...props }) {
        return(
          <Card title="Animal" details={<em>Mammal</em>}>
            <h3>{name}</h3>
            <div>{size}kg</div>
            <AnimalDetails
              {...props}
            />
          </Card>
        )
      }
      ...
      

      Save the file. When you do, the browser will refresh and you’ll see the update, including the phrase Mammal.

      Browser with card and details

      This prop is already powerful because it can take JSX of any size. In this example, you added only a single element, but you could pass as much JSX as you wanted. It also doesn’t have to be JSX. If you have a complicated markup for example, you wouldn’t want to pass it directly in the prop; this would be difficult to read. Instead, you could create a separate component and then pass the component as a prop.

      To see this at work, pass AnimalDetails to the details prop:

      wrapper-tutorial/src/components/AnimalCard/AnimalCard.js

      import React from 'react';
      ...
      
      export default function AnimalCard({ name, size, ...props }) {
        return(
          <Card
            title="Animal"
            details={
              <AnimalDetails
                {...props}
              />
            }
          >
            <h3>{name}</h3>
            <div>{size}kg</div>
          </Card>
        )
      }
      ...
      

      AnimalDetails is more complicated and has a number of lines of markup. If you were to add it directly to details, it would increase the prop substantially and make it difficult to read.

      Save and close the file. When you do, the browser will refresh and the details will appear at the top of the card.

      Card with details at the top

      Now you have a Card component that can take custom JSX and place it in multiple spots. You are not restricted to a single prop; you can pass elements to as many props as you want. This gives you the ability to create flexible wrapping components that can give other developers the opportunity to customize a component while retaining its overall style and functionality.

      Passing a component as a prop isn’t perfect. It’s a little more difficult to read and isn’t as clear as passing children, but they are just as flexible and you can use as many of them as you want in a component. You should use children first, but don’t hesitate to fall back to props if that is not enough.

      In this step, you learned how to pass JSX and React components as props to another component. This will give your component the flexibility to handle many situations where a wrapper component may need multiple props to handle JSX or components.

      Conclusion

      You have created a variety of wrapping components that can display data flexibly while keeping a predictable look and structure. You created components that can collect and pass unknown props to nested components. You also used the built-in children prop to create wrapper components that can handle an arbitrary number of nested elements. Finally, you created a component that can take JSX or React components as a prop so that your wrapper component can handle multiple instances of different customizations.

      Wrapper components give you the ability to adapt to unknown circumstances while also maximizing code reuse and consistency. This pattern is useful for creating basic UI elements that you will reuse throughout an application including: buttons, alerts, modals, slide shows, and more. You’ll find yourself returning to it many times.

      If you would like to look at more React tutorials, check out our React Topic page, or return to the How To Code in React.js series page.



      Source link

      How To Create a Minecraft Server on Ubuntu 18.04


      The author selected the Tech Education Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Minecraft is a popular sandbox video game. Originally released in 2009, it allows players to build, explore, craft, and survive in a block 3D generated world. As of late 2019, it was the second best-selling video game of all time. In this tutorial, you will create your own Minecraft server so that you and your friends can play together. Specifically, you will install the necessary software packages to run Minecraft, configure the server to run, and then deploy the game.

      Alternately, you can explore DigitalOcean’s One-Click Minecraft: Java Edition Server as another installation path.

      This tutorial uses the Java version of Minecraft. If you purchased your version of Minecraft through the Microsoft App Store, you will be unable to connect to this server. Most versions of Minecraft purchased on gaming consoles such as the PlayStation 4, Xbox One, or Nintendo Switch are also the Microsoft version of Minecraft. These consoles are also unable to connect to the server built in this tutorial. You can obtain the Java version of Minecraft here.

      Prerequisites

      In order to follow this guide, you’ll need:

      Step 1 — Installing the Necessary Software Packages and Configure the Firewall

      With your server initialized, your first step is to install Java; you’ll need it to run Minecraft.

      Update the package index for the APT package manager:

      Next, install the OpenJDK version 8 of Java, specifically the headless JRE. This is a minimal version of Java that removes the support for GUI applications. This makes it ideal for running Java applications on a server:

      • sudo apt install openjdk-8-jre-headless

      You also need to use a software called screen to create detachable server sessions. screen allows you to create a terminal session and detach from it, leaving the process started on it running. This is important because if you were to start your server and then close your terminal, this would kill the session and stop your server. Install screen now:

      Now that you have the packages installed we need to enable the firewall to allow traffic to come in to our Minecraft server. In the initial server setup that you performed you only allowed traffic from SSH. Now you need to allow for traffic to come in via port 25565, which is the default port that Minecraft uses to allow connections. Add the necessary firewall rule by running the following command:

      Now that you have Java installed and your firewall properly configured, you will download the Minecraft server from the Minecraft website.

      Step 2 — Downloading the Latest Version of Minecraft

      Now you need to download the current version of the Minecraft server. You can do this by navigating to Minecraft’s Website and copying the link that says Download minecraft_server.X.X.X.jar, where the X’s are the latest version of the server.

      You can now use wget and the copied link to download the server:

      • wget https://launcher.mojang.com/v1/objects/bb2b6b1aefcd70dfd1892149ac3a215f6c636b07/server.jar

      If you intend to upgrade your Minecraft server, or if you want to run different versions of Minecraft, rename the downloaded server.jar to minecraft_server_1.15.2.jar, matching the highlighted version numbers to whatever version you just downloaded:

      • mv server.jar minecraft_server_1.15.2.jar

      If you want to download an older version of Minecraft, you can find them archived at mcversions.net. But this tutorial will focus on the current latest release. Now that you have your download let’s start configuring your Minecraft server.

      Step 3 — Configuring and Running the Minecraft Server

      Now that you have the Minecraft jar downloaded, you are ready to run it.

      First, start a screen session by running the screen command:

      Once you have read the banner that has appeared, press the SPACE bar. screen will present you with a terminal session like normal. This session is now detachable, which means that you’ll be able to start a command here and leave it running.

      You can now perform your initial configuration. Do not be alarmed when this next command throws an error. Minecraft has designed its installation this way so that users must first consent to the company’s licensing agreement. You will do this next:

      • java -Xms1024M -Xmx1024M -jar minecraft_server_1.15.2.jar nogui

      Before examining this command’s output, let’s take a closer look at all these command-line arguments, which are tuning your server:

      • Xms1024M – This configures the server to start running with 1024MB or 1GB of RAM running. You can raise this limit if you want your server to start with more RAM. Both M for megabytes and G for gigabytes are supported options. For example: Xms2G will start the server with 2 gigabytes of RAM.

      • Xmx1024M – This configures the server to use, at most, 1024M of RAM. You can raise this limit if you want your server to run at a larger size, allow for more players, or if you feel that your server is running slowly.

      • jar – This flag specifies which server jar file to run.

      • nogui – This tells the server not to launch a GUI since this is a server, and you don’t have a graphical user interface.

      The first time you run this command, which normally starts your server, it will instead generate the following error:

      Output

      [22:05:31] [22:05:31] [main/ERROR]: Failed to load properties from file: server.properties [22:05:31] [main/WARN]: Failed to load eula.txt [22:05:31] [main/INFO]: You need to agree to the EULA in order to run the server. Go to eula.txt for more info.

      These errors were generated because the server could not find two necessary files required for execution: the EULA (End User License Agreement), found in eula.txt, and the configuration file server.properties. Fortunately, since the server was unable to find these files, it created them in your current working directory.

      First, open eula.txt in nano or your favorite text editor:

      Inside this file, you will see a link to the Minecraft EULA. Copy the URL:

      ~/eula.txt

      #By changing the setting below to TRUE you are indicating your agreement to our EULA (https://account.mojang.com/documents/minecraft_eula).
      #Tue Mar 24 22:05:31 UTC 2020
      eula=false
      

      Open the URL in your web browser and read the agreement. Then return to your text editor and find the last line in eula.txt. Here, change eula=false to eula=true. Now save and close the file.

      Now that you’ve accepted the EULA, it is time to configure the server to your specifications.

      In your current working directory, you will also find the newly created server.properties file. This file contains all of the configuration options for your Minecraft server. You can find a detailed list of all server properties on the Official Minecraft Wiki. You will modify this file with your preferred settings before starting your server. This tutorial will cover the fundamental properties:

      Your file will appear like this:

      ~/server.properties

      #Minecraft server properties
      #Thu Apr 30 23:42:29 UTC 2020
      spawn-protection=16
      max-tick-time=60000
      query.port=25565
      generator-settings=
      force-gamemode=false
      allow-nether=true
      enforce-whitelist=false
      gamemode=survival
      broadcast-console-to-ops=true
      enable-query=false
      player-idle-timeout=0
      difficulty=easy
      spawn-monsters=true
      broadcast-rcon-to-ops=true
      op-permission-level=4
      pvp=true
      snooper-enabled=true
      level-type=default
      hardcore=false
      enable-command-block=false
      max-players=20
      network-compression-threshold=256
      resource-pack-sha1=
      max-world-size=29999984
      function-permission-level=2
      rcon.port=25575
      server-port=25565
      server-ip=
      spawn-npcs=true
      allow-flight=false
      level-name=world
      view-distance=10
      resource-pack=
      spawn-animals=true
      white-list=false
      rcon.password=
      generate-structures=true
      online-mode=true
      max-build-height=256
      level-seed=
      prevent-proxy-connections=false
      use-native-transport=true
      motd=A Minecraft Server
      enable-rcon=false
      

      Let’s take a closer look at some of the most important properties in this list:

      • difficulty (default easy) – This sets the difficulty of the game, such as how much damage is dealt and how the elements affect your player. The options are peaceful, easy, normal, and hard.

      • gamemode (default survival) – This sets the gameplay mode. The options are survival, creative,adventure, and spectator.

      • level-name (default world) – This sets the name of your server that will appear in the client. Characters such as the apostrophe may need to be escaped with a backslash.

      • motd (default A Minecraft Server) – The message that is displayed in the server list of the Minecraft client.

      • pvp (default true) – Enables Player versus Player combat. If set to true, players will be able to engage in combat and damage each other.

      Once you have set the options that you want, save and close the file.

      Now that you have changed EULA to true and configured your settings, you can successfully start your server.

      Like last time, let’s start your server with 1024M of RAM. Only now, let’s also grant Minecraft the ability to use up to 4G of RAM if it needs it. Remember, you are welcome to adjust this number to fit your server limitations or user needs:

      • java -Xms1024M -Xmx4G -jar minecraft_server_1.15.2.jar nogui

      Give the initialization a few moments. Soon your new Minecraft server will start producing an output similar to this:

      Output

      [21:08:14] [Server thread/INFO]: Starting minecraft server version 1.15.2 [21:08:14] [Server thread/INFO]: Loading properties [21:08:14] [Server thread/INFO]: Default game type: SURVIVAL [21:08:14] [Server thread/INFO]: Generating keypair [21:08:15] [Server thread/INFO]: Starting minecraft server on *:25565

      Once the server is up and running, you will see the following output:

      Output

      [21:15:37] [Server thread/INFO]: Done (30.762s)! For help, type "help"

      Your server is now running, and you have been dropped into the server administrator control panel. Now type help:

      An output like this will appear:

      Output

      [21:15:37] [Server thread/INFO]: /advancement (grant|revoke) [21:15:37] [Server thread/INFO]: /ban <targets> [<reason>] [21:15:37] [Server thread/INFO]: /ban-ip <target> [<reason>] [21:15:37] [Server thread/INFO]: /banlist [ips|players] ...

      From this terminal you can execute administrator commands and control your Minecraft server. Now let’s use screen to keep your new server running, even after you log out. Then you can connect to your Minecraft client and start a new game.

      Step 4 — Keeping the Server Running

      Now that you have your server up, you want it to remain running even after you disconnect from your SSH session. Since you used screen earlier, you can detach from this session by pressing Ctrl + A + D. Now you’re back in your original shell.

      Run this command to see all of your screen sessions:

      You’ll get an output with the ID of your session, which you’ll need to resume that session:

      Output

      There is a screen on: 26653.pts-0.minecraft (03/25/20 21:18:31) (Detached) 1 Socket in /run/screen/S-root.

      To resume your session, pass the -r flag to the screen command and then enter your session ID:

      When you are ready to log out of your server, be sure to detach from the session with Ctrl + A + D and then log out.

      Step 5 — Connecting to Your Server from the Minecraft Client

      Now that your server is up and running, let’s connect to it through the Minecraft client. Then you can play!

      Launch your copy of Minecraft Java Edition and select Multiplayer in the menu.

      Select Multiplayer in the menu

      Next, you will need to add a server to connect to, so click on the Add Server button.

      Click the Add Server button

      In the Edit Server Info screen that shows up, give your server a name and type in the IP address of your server. This is the same IP address that you used to connect through SSH.

      Name your server and type in the IP address

      Once you have entered your server name and IP address, you’ll be taken back to the Multiplayer screen where your server will now be listed.

      Select your server and click Join Server

      From now on, your server will always appear in this list. Select it and click Join Server.

      Enjoy the game!

      You are in your server and ready to play!

      Conclusion

      You now have a Minecraft server running on Ubuntu 18.04 for you and all of your friends to play on! Have fun exploring, crafting, and surviving in a crude 3D world. And remember: watch out for griefers.



      Source link