Set Default Inputs on a NextJS Typescript Function

Set Default Inputs on a NextJS Typescript Function

Let’s quickly go over how to set default inputs on a NextJS Typescript function. This will be short and to the point. No need to waste your time.

  1. We want to type hint because TypeScript and Webstorm will yell at us if we don’t.
  2. This isn’t specific to NextJS. This is for TypeScript functions in general.

The Why I Need to Set a Default

So, I wanted to dynamically set the autofocus of a custom input in my tool. But when I added in the parameter I didn’t want to explicitly define whether an input should autofocus 100% of the time. I’m lazy. I’d then take that autoFocus param that I’m defaulting to false and pass it along to my actual autoFocus param in my input.

How To Set Default Inputs on a NextJS Typescript Function or Component

Let’s type hint and define our function’s interface.

interface CustomInputProps {
    autoFocus?: boolean;
}

This is the interface for my CustomInput functional component. This is saying that the function takes an optional autoFocus param. We say it’s optional with the “?” after the param name. But still there’s no default. Let’s get that chunk in our code.

interface CustomInputProps {
    autoFocus?: boolean;
}

const CustomInput = ({autoFocus=false}: CustomInputProps) => {
  return (
    <div
      style={{
        flexDirection: "row",
        justifyContent: "space-between",
        alignItems: "center",
        display: "flex",
        margin: "10px",
      }}
    >
      <input type={"text"} style={{ marginRight: 10, fontSize: 30, minWidth: 200 }} autoFocus={autoFocus}/>
    </div>
  );
};

export default CustomInput;

Here’s my larger functional component. You can now see that we set the autoFocus param to false with {autoFocus=false}. Then we pass our functional component our interface so that we know what params to pass the function during development. This should work regardless of type for framework as long as your using Typescript functions. Check out this blog post for making custom buttons in NextJS.