Tuesday, December 28, 2021

Two-way binding input in React

As a follow-up to my big disappointment with Vue due to the lack of typed emits, even with TypeScript, I came back to think about a two-way binding input in React. Turns out, it’s pretty trivial to implement.

import { useState } from 'react';
	
interface TwoWayValue {
	value: string;
	setValue: (value: string) => void;
}

interface Props {
	data: TwoWayValue;
}

function TwoWayInput(props: Props) {
	return <input type="text" value={props.data.value}
		onChange={e => props.data.setValue(e.target.value)} />;
}

function useTwoWayState(initialValue: string): TwoWayValue {
	const [value, setValue] = useState(initialValue);
	return { value, setValue };
}

export { TwoWayValue, TwoWayInput, useTwoWayState };

Usage:

import { TwoWayInput, useTwoWayState } from 'two-way-input';

function App() {
	const nome = useTwoWayState('');

	return <div>
		<h1>{nome.value}</h1>
		<TwoWayInput type="text" data={nome} />
	</div>;
}

Now I’m still wondering about scoped CSS.

No comments: