简体   繁体   中英

How to check if front matter empty or not in Gatsby

Let's just say I have a source of content that comes from markdown and yaml with front matter that sometimes has empty value. For example:

# front matter
title: Foo
subtitle:
// foo.js
import React from 'react';

const Foo = ({data}) => {
    return(
       // check if {data.subtitle} not empty 
       // <p>{data.subtitle}/p>
       // else
       // ...
    )
}

export default Foo;

I wonder what is the best way to to check the value of the front matter. Is it through conditional statements (if else) in the jsx template?

The main goal is that Gatsby only renders some elements if the value of a particular front matter is not empty

There are two common patterns for conditional rendering in JSX:

  1. If you only want to render if true (or if not true), use && :

     {data.subtitle && <p>{data.subtitle}</p>} // or {!renderDisabled && <p>Something</p>}

    Note that in the second case you're not using || ; this is because if the left hand side of the statement is truthy it will be returned and rendered, and you probably don't intend to output something like <div>true</div> .

  2. If you want to render one of two different branches depending on the condition, use a ternary:

     {data.subtitle? <p>{data.subtitle}</p>: <p>Default subtitle</p>}

I guess this is stylistic but the most terse way would be a ternary

return data.subtitle? <p>{data.subtitle}</p>:<>Whatever else </>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM