Make your JavaScript code reusable with this one simple trick

This is a little trick I've used for a while now, but not many of my peers seemed to know about it.

This week whilst at work I've had 2 separate developers ask me about it, and question whether it actually works, so I thought it would make a nice quick blog post.

 

To demonstrate it I'll use it in a React component, however, it is not something specific to React, but native to JavaScript.

 

Below is a simple contact form component, the main part from this we want is the onInputChange() function.

import React, { useState } from 'react';

interface FormData {
    name: string;
    email: string;
    content: string;
}

export function ContactForm(): JSX.Element {
    const [formData, setFormData] = useState<FormData>({
        name: '',
        email: '',
        content: '',
    });

    const onFormSubmit = (e: React.SyntheticEvent): void => {
        e.preventDefault();
        alert('Let\'s just pretend I sent this to a server, okay?');
    }

    const onInputChange = (target: string, value: string): void => {
        setFormData({...formData, [target]: value});
    }

    return <form onSubmit={onFormSubmit}>
        <div>
            <label htmlFor='name'>Name:</label>
            <input type="text" id='name' value={formData.name} onChange={(e) => onInputChange('name', e.target.value)} />
        </div>

        <div>
            <label htmlFor='email'>Email:</label>
            <input type="text" id='email' value={formData.email} onChange={(e) => onInputChange('email', e.target.value)} />
        </div>

        <div>
            <label htmlFor='content'>Message:</label>
            <textarea name="" id="content" cols="30" rows="10" onChange={(e) => onInputChange('content', e.target.value)}></textarea>
        </div>
        
        <input type="submit" value='Send' />
    </form>;
}

The trick here is that when we call setFormData() we are creating a new object, passing all of the content from the old formData variable by using the spread syntax, but then doing [target]: value.

All this does is uses the bracket notation to target a key, and then set its value.

The bracket notation is the exact same as doing the following:

const person = {
    name: 'Cory',
    age: '28',
}

person['name'] = 'Bob';

 

It's a cool little trick that helps to reduce repetitive code, but I was surprised at the amount of people around me that hadn't seen this syntax before. So there you have it.