Categories
Vue Answers

How to Run the Vue.js Dev Server via HTTPS?

Sometimes, we want to run the Vue CLI dev server via HTTPS.

In this article, we’ll look at how to run the Vue CLI dev server via HTTPS.

Run Vue.js Dev Server with HTTPS

We can change the Vue dev server’s config to serve the project over HTTPS rather than HTTP.

To do that, we read the private key and certificate.

And we set the URL to serve the project on.

For instance, we can write:

const fs = require('fs')

module.exports = {
  devServer: {
    https: {
      key: fs.readFileSync('./certs/key.pem'),
      cert: fs.readFileSync('./certs/cert.pem'),
    },
    public: 'https://localhost:8888/'
  }
}

We read in the files and set them as the properties of the https property.

To make a certificate, we can use the mkcert program to do it.

We can install it on Windows, Mac OS, or Linux by following the instructions on https://github.com/FiloSottile/mkcert.

Then we can create a new key and certificate by running:

mkcert -install

and:

mkcert example.com "*.example.com" example.test localhost 127.0.0.1 ::1

Then we created a certificate valid for localhost.

We just copy the files to the cert folder and rename them to match what we have in the config.

Then we can run npm run dev and serve the project.

Conclusion

We can change the Vue dev server’s config to serve the project over HTTPS rather than HTTP.

Categories
Vue Answers

How to Open a Link in a New Tab with Vue Router?

Sometimes, we want to open a link in a new window with Vue Router.

In this article, we’ll look at how to open a link in a new window with Vue Router.

Open a Link in a New Tab with Vue Router

We can open a link in a new tab with Vue Router.

For instance, we can write:

const routeData = this.$router.resolve({ name: 'foo', query: { data: "bar" }});
window.open(routeData.href, '_blank');

We call the this.$router.resolve method to get the URL to open.

Then we call window.open to open the given URL.

The first argument is the URL.

'_blank' indicates that we open the URL in a new tab.

Conclusion

We can open a link in a new tab with Vue Router.

Categories
React Answers

How to Cache Computed Values with the React useMemo Hook?

We can use the React useMemo hook to cache computed values.

In this article, we’ll look at how to use the React useMemo hook to cache computed values.

Memoize Values with the React useMemo Hook

We can also use the useMemo hook to create a memoized values, which means that it’s cached as long as it or its dependencies don’t change.

useMemo runs during rendering. Therefore, we shouldn’t run anything that we wouldn’t do during rendering.

It’s used as a performance optimization, but it’s not a guarantee of the integrity of the value because it might change later.

For instance, we can use it as follows:

import React from "react";

export default function App() {
  const [firstName, setFirstName] = React.useState("");
  const [lastName, setLastName] = React.useState("");
  const name = React.useMemo(() => `${firstName} ${lastName}`, [
    firstName,
    lastName
  ]);

  return (
    <div>
      <input value={firstName} onChange={e => setFirstName(e.target.value)} />
      <input value={lastName} onChange={e => setLastName(e.target.value)} />
      <p>{name}</p>
    </div>
  );
}

In the code above, we used useMemo to watch firstName and lastName ‘s values and then derive a new value name from combining the 2.

Then when we enter text into the input, we’ll see that it updates the value of name . However, it’ll cache the existing value if firstName or lastName don’t change.

Conclusion

We can also use the useMemo hook to create a memoized values, which means that it’s cached as long as it or its dependencies don’t change.

Categories
React Answers

How to Add Refs to React Components by Forwarding Refs?

Sometimes, we want to add refs to React components.

In this article, we’ll look at how to add refs to React components.

Add Refs to React Components by Forwarding Refs

Forwarding refs means that we are getting the refs from a child component from a parent component.

For instance, if we want to get the ref of a button that resides in a custom button component, we can write the following code:

import React, { useEffect } from "react";

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref}>{props.children}</button>
));

export default function App() {
  const buttonRef = React.createRef();

  useEffect(() => {
    buttonRef.current.focus();
  }, []);

  return (
    <>
      <FancyButton ref={buttonRef}>Click me!</FancyButton>;
    </>
  );
}

In the code above, we have the FancyButton component, which has the button element, which we want to access. To let us access it from App or another component, we call React.forwardRef , which takes a callback with 2 parameters, props and ref .

The props have the props, and the ref is the ref that we can access from the outside. We set the ref prop to the ref parameter so to set the ref to the button.

Then in App , we create the buttonRef and pass it into ref . Then in the useEffect callback, we call buttonRef.current.focus(); to focus the button when App load since we have an empty array as the 2nd argument.

Forwarding refs are also used with 3rd party components. For instance, if we have to use the react-hook-form package and we’re using our own custom input control components, then we have to call forwardRef as follows:

import React from "react";
import { useForm } from "react-hook-form";

const Select = React.forwardRef(({ label }, ref) => (
  <>
    <label>{label}</label>
    <select name={label} ref={ref}>
      <option value="10">10</option>
      <option value="20">20</option>
    </select>
  </>
));

export default function App() {
  const { register, handleSubmit } = useForm();

  const onSubmit = () => {};

  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)}>
        <Select label="Age" ref={register} />
        <input type="submit" />
      </form>
    </>
  );
}

In the code above, we created a custom select control called Select , which is created by calling forwardRef with a callback that takes the ref as the 2nd parameter, we set it as the value of the ref prop in the select element.

Then we can access the ref of select from App .

Conclusion

Forwarding refs means that we are getting the refs from a child component from a parent component.

Categories
React Answers

How to Use Prop Types to Check to Validate React Compoennt Prop Data

Checking data types for React component props lets us prevent many mistakes in our code.

In this article, we’ll look at how to check data types for React component props.

Use Prop Types to Check to Validate React Compoennt Prop Data

By default, React lets us pass anything from parent components to child components via props. This isn’t ideal because it’s very easy to make a mistake that may cause runtime errors in production.

Therefore, we should use React’s built-in prop-type validation feature to check the data type of props. We can also use it to check if the prop value has the format that we want them to be in.

There’s built-in prop type for common JavaScript data types. In addition, we can check for a combination of one or more types and we can also pass in a custom validation to check for the prop data.

For instance, we can use it as follows:

import React from "react";
import PropTypes from "prop-types";

const Foo = ({ data }) => {
  return <p>{data}</p>;
};

Foo.propTypes = {
  data: PropTypes.string
};

export default function App() {
  return <Foo data="bar" />;
}

In the code above, we have:

Foo.PropTypes = {
  data: PropTypes.string
};

to check that the data prop is indeed a string. In the code above, we passed in a string as the value of the data prop. Therefore, we should see the p element displayed with the text ‘bar’ inside.

Otherwise, we would get an error.

We can add our own prop data validation as follows:

import React from "react";

const Foo = ({ data }) => {
  return <p>{data}</p>;
};

Foo.propTypes = {
  data(props, propName, componentName) {
    if (!/bar/.test(props[propName])) {
      return new Error("I want bar");
    }
  }
};

export default function App() {
  return <Foo data="baz" />;
}

In the code above, we have:

Foo.propTypes = {
  data(props, propName, componentName) {
    if (!/bar/.test(props[propName])) {
      return new Error("I want bar");
    }
  }
};

Therefore, if we didn’t pass in 'bar' as the value of the data prop into Foo , we’ll get the error ‘I want bar’ logged in the console. We pass in 'baz' , so we’ll get the error.

Conclusion

By default, React lets us pass anything from parent components to child components via props. This isn’t ideal because it’s very easy to make a mistake that may cause runtime errors in production.

Therefore, we should use React’s built-in prop-type validation feature to check the data type of props. We can also use it to check if the prop value has the format that we want them to be in.