emred2700
emred2700

Reputation: 59

Layout mismatch between development & build in Gatsby

I am using Gatsby and source my data from Airtable plugin. I also use gatsby-image for lazy loading and stuff. The problem is that the render is correct in gatsby develop, But when I gatsby build, the second item of the airtable data is taking the first spot with broken UI. It only gets fixed when I click another gatsby link and click back to the homepage.

I think it's caused by gatsby-image but I just don't understand what's wrong with it. Here's the deployed preview: https://5f97de1908aca50007e75d94--hey-gamer.netlify.app/

enter image description here

Upvotes: 1

Views: 237

Answers (1)

Derek Nguyen
Derek Nguyen

Reputation: 11577

This often happens when you're doing something 'illegal' with your HTML structure, i.e <div> as direct descendant of <ul>, <button> inside <button>, etc.

In your case, you're having nested <a>. When you have this html:

<a href="#foo">Hi!
  <a href="#bar">Hello!</a>
</a>

The browser will move the inner link out so that both links are under the same parent:

<a href="#foo">Hi!</a>
<a href="#bar">Hello!</a>

If you open your site without javascript, this is what you'll see: enter image description here

The browser has done you a 'favor' and fixed your nested anchors for you!


Why it works with React

Now, this happens when a browser parses your html. What happens if you manually nest the anchor tags with javascript?

<a id="one" href="#foo">Hi!</a>
<a id="two" href="#bar">Hello!</a>

<script>
  let $a1 = document.getElementById('one')
  let $a2 = document.getElementById('two')

  $a1.appendChild($a2)
</script>

It doesn't care, so you can actually have nested anchors... if you fiddle with the DOM after it has loaded.

This is why your Gatsby-prerendered page looks kinda normal. When React showed up, it was smart enough to reshape the DOM for you, but it still made a mistake: your 2nd anchor was appended to the wrong node.

When you came into this page from another link, Gatsby didn't pre-render the HTML for you, so React just happily produced the structure that the browser deemed illegal.

What to do

You should fix your structure, don't wrap the card with an anchor tag. If your card must be clickable, you could make it clickable manually instead of using an anchor tag & deal with the a11y issues, or use CSS to make the anchor tags appear to be nested (with absolute positioning for example) eventhough they're siblings.

Here's a CSSTrick article on this issue: Nested Links

Upvotes: 2

Related Questions