最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Understanding the use of && in a react component - Stack Overflow

programmeradmin1浏览0评论

I am trying to understand this functional ponent in react. I know Post accepts two parameters post and excerpt. 2 tenary operators were used

Here is the render code from a ponent that uses post.

        const renderPosts = () => {
            if (loading) return <p>Loading posts...</p>
            if (hasErrors) return <p>Unable to display posts.</p>

            return posts.map(post => <Post key={post.id} post={post} excerpt />)
        }

I don't understand what (excerpt &&) is doing together with the Link below. Can you explain this to me? Also passing excerpt from the map helper above, what does that imply? It has no value.

        export const Post = ({ post, excerpt }) => (
          <article className={excerpt ? 'post-excerpt' : 'post'}>
            <h2>{post.title}</h2>
            <p>{excerpt ? post.body.substring(0, 100) : post.body}</p>

            {excerpt && (
              <Link to={`/posts/${post.id}`} className="button">
                View Post
              </Link>
            )}
          </article>
        )

I am trying to understand this functional ponent in react. I know Post accepts two parameters post and excerpt. 2 tenary operators were used

Here is the render code from a ponent that uses post.

        const renderPosts = () => {
            if (loading) return <p>Loading posts...</p>
            if (hasErrors) return <p>Unable to display posts.</p>

            return posts.map(post => <Post key={post.id} post={post} excerpt />)
        }

I don't understand what (excerpt &&) is doing together with the Link below. Can you explain this to me? Also passing excerpt from the map helper above, what does that imply? It has no value.

        export const Post = ({ post, excerpt }) => (
          <article className={excerpt ? 'post-excerpt' : 'post'}>
            <h2>{post.title}</h2>
            <p>{excerpt ? post.body.substring(0, 100) : post.body}</p>

            {excerpt && (
              <Link to={`/posts/${post.id}`} className="button">
                View Post
              </Link>
            )}
          </article>
        )
Share Improve this question edited Dec 22, 2021 at 22:46 Shorn 21.7k17 gold badges107 silver badges202 bronze badges asked Apr 12, 2020 at 2:13 BabaBaba 2,2299 gold badges53 silver badges94 bronze badges 1
  • Try not to ask multiple questions in a single question. SO is designed for "one question, one answer" - you can only mark one answer as "correct". There's nothing wrong with posting multiple fine-grained questions to SO, you can even cross reference the questions if you want to avoid having to post all the details multiple times. Posting single questions helps you get your answers quicker, helps others more easily answer the parts of your question that they understand and keeps answers easier to read. – Shorn Commented Apr 12, 2020 at 3:43
Add a ment  | 

5 Answers 5

Reset to default 3

You posted this question with reactjs as the only tag, indicating you think this is a react thing, but fundamentally your question is about a javascript thing: "Short circuit conditionals".

From the code you posted:

excerpt && <Link ...>

is expressing

if excerpt 
  then return <Link ...> 
  else return undefined

So if excerpt evaluates "falsy", nothing will be displayed (because React ignores undefined or null), but if excerpt is "truthy" then the link will be displayed.


EDIT:

I just noticed you had a second question in there:

Also passing excerpt from the map helper above, what does that imply? It has no value.

Omitting the value of an attribute causes JSX to treat it as true. See this SO answer elsewhere.

So that bit of code is expressing that it wants the Post ponent to always add the Link.

Note your second question is actually very react-specific, given that React goes out of its way to define these "empty" attributes as "truthy", when the default behaviour of HTML treats them as "falsy" - see this SO answer for more details.

if excerpt is true (truthy) the Link will be displayed. The && operator executes once the condition is met.

At Post ponent (below one) && operator will be true if both conditions are true that means excerpt should exist then only Link will work. Second, passing the excerpt through the map will give the value for different post and excerpt has value you have passed it as an argument in Post ponent.

I don't understand what (excerpt &&) is doing together with the Link below.
Can you explain this to me?

It is called Conditional Rendering in react, a very powerful concept.
It enables you to render ponents depending on the state of your application.

// In JavaScript
true && expression === expression 

false && expression === false.

// Within your code
// if excerpt === true
{excerpt && (<Link>...</Link>)} === (<Link>...</Link>) // Component is rendered

// if excerpt === false
{excerpt && (<Link>...</Link>)} === false  // Component isn't be rendered

Based on the above, you should now understand why excerpt is passed to every Post, excerpt must be a boolean in this implementation.

Have a read of Logical_Operators.

Operator: Logical AND (&&)
Syntax: expr1 && expr2
Description: If expr1 can be converted to true, returns expr2; else, returns expr1.

And then take a look at the Inline If with Logical && Operator section on the react docs conditional-rendering page.

function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }
    </div>
  );
}

const messages = ['React', 'Re: React', 'Re:Re: React'];
ReactDOM.render(
  <Mailbox unreadMessages={messages} />,
  document.getElementById('root')
);

It works because in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false.

Therefore, if the condition is true, the element right after && will appear in the output. If it is false, React will ignore and skip it.

发布评论

评论列表(0)

  1. 暂无评论