Display initial element in React for bots and screen readers

Viewed 261

Thinking about accessibility and crawlers, let's say I have a dynamic component that updates every second.

<LiveComponent />

output:

<div id="live">
  <!-- Something that changes very frequently -->
</div>

However, if someone has a screen reader, or if a bot crawls it, the constantly updating component won't be very helpful. I'd rather show something like a snapshot, summary, or alternative piece of information on that very first paint that bots will grab, and screenreaders will process, but won't be visible to the user. (Prefer to not have a flash of refresh.):

<div id="live">
  <p>This is a static version of the dynamic data that's just as informative</p>
</div>

Possible options:

  • useEffect(()=>{ }, []); tied to a display class... but hiding / revealing elements with CSS will clutter things up (both bits of info will be seen by bots / readers)
  • Conditional-rendering: won't work (I think) because I need this to be client side...
3 Answers

I would use a different <div class="accessibility-live"> for accessibility and put there the static version of the dynamic data. You can use CSS: position absolute off-screen, something like:

.accessibility-live {
position: absolute;
left: -9999em;
}

So the content will be part of the DOM and detected by assistive technologies and crawlers.

Then you can use aria-hidden for your #live div: <div aria-hidden="true" id="live" >

Here you can read more about the aria-hidden attribute.

If I got you right, adding to @AleDP, you may review React-Accessibility I believe the half of the work, you need to do within the reducer,

within the reducer you need to return both current and snapshot values

// your reducer here
const main = (state = initialState, action) => {
  switch (action.type) {
    case API_CALL_SUCCESS:

      let snapshot= youfunctionhere(action.payload.data)

      return { ...state,   snapshot_info:snapshot,live_info:action.payload.data  };
    default:
      return state;

  }
}

// in your rendered

<p>
  this.props.snaphot_info <span aria-hidden="true">this.props.live_info</span>!
</p>

How about this when I want to show and hide the UI that follows by another data I will use useState to handle the state of change

Ex :

const [data, setData] = useState({isShow: true})';

<div>
{
   (data.isShow)? <p>show your content here</p> : ""
}
</div>

This will hide and show content when the data in useState change

Related