Skip to content

Instantly share code, notes, and snippets.

@joshuaslate
Created January 3, 2020 07:49
Show Gist options
  • Save joshuaslate/429367588929380dd222afcb536c173e to your computer and use it in GitHub Desktop.
Save joshuaslate/429367588929380dd222afcb536c173e to your computer and use it in GitHub Desktop.
React Hook for Generated HTML ID (useful for accessible component implementation)
import React from 'react';
import { useGeneratedHtmlId } from './use-generated-html-id';
export const SampleComponent = () => {
const id = useGeneratedHtmlId('sample');
return (
<>
<label htmlFor={id}>Sample component</label>
<input id={id} type="text" />
</>
);
}
import { useRef } from 'react';
export const generateHtmlId = (prefix) =>
`${prefix}-${Date.now()
.toString(36)
.substr(3, 10)}`;
export const useGeneratedHtmlId = (prefix) => {
const idRef = useRef(null);
if (!idRef.current) {
idRef.current = generateHtmlId(prefix);
}
return idRef.current;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment