Commit ee1a7667 authored by Mickaël Bourgier's avatar Mickaël Bourgier
Browse files

[TextField] Associate the label to the input

parent b6429263
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { randAlphaNum } from '@webf/core';
import { withStyles } from '../styles';
import styles from './TextField.styles';
......@@ -9,6 +10,8 @@ import styles from './TextField.styles';
* @summary Champ de texte avec label superposable
*/
class TextField extends Component {
randomId = `text-input-${randAlphaNum(8)}`;
state = {
focused: false
};
......@@ -21,6 +24,7 @@ class TextField extends Component {
disableUnderline,
error,
fullWidth,
id = this.randomId,
label,
placeholder,
readOnly,
......@@ -58,20 +62,23 @@ class TextField extends Component {
return (
<div className={className}>
{label && type !== 'file' ? (
<label className={labelClassName}>{label}</label>
<label className={labelClassName} htmlFor={id}>
{label}
</label>
) : null}
<input
{...otherProps}
className={inputClassName}
aria-invalid={error}
className={inputClassName}
disabled={disabled}
value={value}
id={id}
onBlur={this.handleBlur}
onFocus={this.handleFocus}
placeholder={placeholder}
readOnly={readOnly}
required={required}
type={type}
value={value}
/>
</div>
);
......@@ -128,6 +135,12 @@ TextField.propTypes = {
*/
fullWidth: PropTypes.bool,
/**
* Attribut `id` de l'élément `input` sous-jacent, aussi utilisé pour
* l'attribut `htmlFor` du label (généré aléatoirement par défaut)
*/
id: PropTypes.string,
/**
* Label affiché sur le champ (ou au dessus lorsqu'il n'est pas vide)
*/
......
import React from 'react';
import { cleanup, render } from '@testing-library/react';
import wrapToTest from '../utils/wrapToTest';
import TextField from './TextField';
describe('<TextField />', () => {
afterEach(cleanup);
describe('id prop', () => {
it('must set the `for` html attribute on the label', () => {
const { getByLabelText, getByText } = render(
wrapToTest()(<TextField label='Text field' />)
);
const label = getByText(/Text field/);
const input = getByLabelText(/Text field/);
expect(input).toHaveAttribute('id');
expect(label).toHaveAttribute('for', input.id);
});
});
});
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment