Accessibility in React.js

The aria-* attributes on html elements are also supported in React.js as well. The other attributes are generally written in camel-case but these aria-* are written in hyphen-cased.

Sometimes we break the semantics of the html if we use parent div in React.js

Example

render(){
   return(
      
         

Test

     
   ); }

Div can cause semantics issue if working with table, list etc. To avoid this we can use React provided fragment as shown below −

import React, { Fragment } from ‘react’;
function MessageList({ message }) {
   return (
      
         
{ message.key }
         
{message.description}
     
   ); }

We can also use it with map a collection of items to an array of fragments −

function MessageList(props) {
   return (
      
         {props.messages.map( message => (             // Fragments should also have a `key` prop when mapping collections                            
{message.from}
               
{message.To}
           
         ))}      
   ); }

The short syntax of fragment is writing just >>

import React, { Fragment } from ‘react’;
function MessageList({ message }) {
   return (
      
         
{ message.key }
         
{message.description}
      >    ); }

Labeling in forms

Instead of writing for attribute in label, we write it as htmlFor


Focus control with ref −

We can create ref as −

This.userInput = React.createRef();
getFocus() {
   // Explicitly focus the text input using the raw DOM API
   // Note: we're accessing "current" to get the DOM node
   this.userInput.current.focus();
}

To work the ref through the higher order components, its needed to use forward ref.

Updated on: 2019-08-28T09:12:18+05:30

469 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements