react - conditional rendering inside component return function












2














I would like to understand why react behaves this way.



This works





class Feed extends React.Component {
constructor(props) {
super(props);
}

render() {
const posts = [{ id: 1, title: 'post-1' }, { id: 2, title: 'post-2' }];
return (
<>
{posts.map(post => (
<Post key={post.id} title={post.title} />
))}
</>


But this doesn't



class Feed extends React.Component {
constructor(props) {
super(props);
}

render() {
const posts = [{ id: 1, title: 'post-1' }, { id: 2, title: 'post-2' }];
return (
<>
{posts.map(post => {
// changes are here
if (post.id < 2) {
<Post key={post.id} title={post.title} />;
}
})}
</>


It just returns blank. No errors.



What is the reason react isn't rendering this? And what would be the best approach to only render post-1?










share|improve this question





























    2














    I would like to understand why react behaves this way.



    This works





    class Feed extends React.Component {
    constructor(props) {
    super(props);
    }

    render() {
    const posts = [{ id: 1, title: 'post-1' }, { id: 2, title: 'post-2' }];
    return (
    <>
    {posts.map(post => (
    <Post key={post.id} title={post.title} />
    ))}
    </>


    But this doesn't



    class Feed extends React.Component {
    constructor(props) {
    super(props);
    }

    render() {
    const posts = [{ id: 1, title: 'post-1' }, { id: 2, title: 'post-2' }];
    return (
    <>
    {posts.map(post => {
    // changes are here
    if (post.id < 2) {
    <Post key={post.id} title={post.title} />;
    }
    })}
    </>


    It just returns blank. No errors.



    What is the reason react isn't rendering this? And what would be the best approach to only render post-1?










    share|improve this question



























      2












      2








      2







      I would like to understand why react behaves this way.



      This works





      class Feed extends React.Component {
      constructor(props) {
      super(props);
      }

      render() {
      const posts = [{ id: 1, title: 'post-1' }, { id: 2, title: 'post-2' }];
      return (
      <>
      {posts.map(post => (
      <Post key={post.id} title={post.title} />
      ))}
      </>


      But this doesn't



      class Feed extends React.Component {
      constructor(props) {
      super(props);
      }

      render() {
      const posts = [{ id: 1, title: 'post-1' }, { id: 2, title: 'post-2' }];
      return (
      <>
      {posts.map(post => {
      // changes are here
      if (post.id < 2) {
      <Post key={post.id} title={post.title} />;
      }
      })}
      </>


      It just returns blank. No errors.



      What is the reason react isn't rendering this? And what would be the best approach to only render post-1?










      share|improve this question















      I would like to understand why react behaves this way.



      This works





      class Feed extends React.Component {
      constructor(props) {
      super(props);
      }

      render() {
      const posts = [{ id: 1, title: 'post-1' }, { id: 2, title: 'post-2' }];
      return (
      <>
      {posts.map(post => (
      <Post key={post.id} title={post.title} />
      ))}
      </>


      But this doesn't



      class Feed extends React.Component {
      constructor(props) {
      super(props);
      }

      render() {
      const posts = [{ id: 1, title: 'post-1' }, { id: 2, title: 'post-2' }];
      return (
      <>
      {posts.map(post => {
      // changes are here
      if (post.id < 2) {
      <Post key={post.id} title={post.title} />;
      }
      })}
      </>


      It just returns blank. No errors.



      What is the reason react isn't rendering this? And what would be the best approach to only render post-1?







      reactjs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 13 '18 at 3:25









      Nguyễn Thanh Tú

      4,6193827




      4,6193827










      asked Nov 13 '18 at 3:16









      dariuscosden

      6818




      6818
























          4 Answers
          4






          active

          oldest

          votes


















          2














          The arrow function syntax can accept either a value to return, or a block of code to execute. In the first example, you give a value: <Post key={post.id} title={post.title} />. However, in the second example you give a code block (by using {}). So, you need to either add return before <Post key={post.id} title={post.title}>like so:



          {posts.map(post => {
          if (post.id < 2) {
          return <Post key={post.id} title={post.title} />;
          }
          })}


          or change the if into an && to keep the implicit return behavior:



          {posts.map(post =>
          (post.id < 2) && <Post key={post.id} title={post.title} />
          }





          share|improve this answer





















          • It makes sense now. I was always omitting the second return statement. Thanks for clarifying.
            – dariuscosden
            Nov 13 '18 at 3:52



















          2














          You have to change it to return <Post ... />;






          share|improve this answer





























            2














            You didn't return anything in the map function argument. You can do that easily with a ternary expression and using es6 arrow notation:



             posts.map(post => (post.id < 2) ? <Post key={post.id} title={post.title} /> : null)





            share|improve this answer



















            • 1




              The ternary expression you used is incorrect. Please check my edit
              – Hemadri Dasari
              Nov 13 '18 at 3:44



















            1














            The second didn't work because you forgot the return statement.



            Try this:



              <>
            {posts.map(post => {
            // changes are here
            if (post.id < 2) {
            return <Post key={post.id} title={post.title} />; //added return statement
            }
            })}
            </>





            share|improve this answer





















              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53273283%2freact-conditional-rendering-inside-component-return-function%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              2














              The arrow function syntax can accept either a value to return, or a block of code to execute. In the first example, you give a value: <Post key={post.id} title={post.title} />. However, in the second example you give a code block (by using {}). So, you need to either add return before <Post key={post.id} title={post.title}>like so:



              {posts.map(post => {
              if (post.id < 2) {
              return <Post key={post.id} title={post.title} />;
              }
              })}


              or change the if into an && to keep the implicit return behavior:



              {posts.map(post =>
              (post.id < 2) && <Post key={post.id} title={post.title} />
              }





              share|improve this answer





















              • It makes sense now. I was always omitting the second return statement. Thanks for clarifying.
                – dariuscosden
                Nov 13 '18 at 3:52
















              2














              The arrow function syntax can accept either a value to return, or a block of code to execute. In the first example, you give a value: <Post key={post.id} title={post.title} />. However, in the second example you give a code block (by using {}). So, you need to either add return before <Post key={post.id} title={post.title}>like so:



              {posts.map(post => {
              if (post.id < 2) {
              return <Post key={post.id} title={post.title} />;
              }
              })}


              or change the if into an && to keep the implicit return behavior:



              {posts.map(post =>
              (post.id < 2) && <Post key={post.id} title={post.title} />
              }





              share|improve this answer





















              • It makes sense now. I was always omitting the second return statement. Thanks for clarifying.
                – dariuscosden
                Nov 13 '18 at 3:52














              2












              2








              2






              The arrow function syntax can accept either a value to return, or a block of code to execute. In the first example, you give a value: <Post key={post.id} title={post.title} />. However, in the second example you give a code block (by using {}). So, you need to either add return before <Post key={post.id} title={post.title}>like so:



              {posts.map(post => {
              if (post.id < 2) {
              return <Post key={post.id} title={post.title} />;
              }
              })}


              or change the if into an && to keep the implicit return behavior:



              {posts.map(post =>
              (post.id < 2) && <Post key={post.id} title={post.title} />
              }





              share|improve this answer












              The arrow function syntax can accept either a value to return, or a block of code to execute. In the first example, you give a value: <Post key={post.id} title={post.title} />. However, in the second example you give a code block (by using {}). So, you need to either add return before <Post key={post.id} title={post.title}>like so:



              {posts.map(post => {
              if (post.id < 2) {
              return <Post key={post.id} title={post.title} />;
              }
              })}


              or change the if into an && to keep the implicit return behavior:



              {posts.map(post =>
              (post.id < 2) && <Post key={post.id} title={post.title} />
              }






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 13 '18 at 3:31









              neonfuz

              1694




              1694












              • It makes sense now. I was always omitting the second return statement. Thanks for clarifying.
                – dariuscosden
                Nov 13 '18 at 3:52


















              • It makes sense now. I was always omitting the second return statement. Thanks for clarifying.
                – dariuscosden
                Nov 13 '18 at 3:52
















              It makes sense now. I was always omitting the second return statement. Thanks for clarifying.
              – dariuscosden
              Nov 13 '18 at 3:52




              It makes sense now. I was always omitting the second return statement. Thanks for clarifying.
              – dariuscosden
              Nov 13 '18 at 3:52













              2














              You have to change it to return <Post ... />;






              share|improve this answer


























                2














                You have to change it to return <Post ... />;






                share|improve this answer
























                  2












                  2








                  2






                  You have to change it to return <Post ... />;






                  share|improve this answer












                  You have to change it to return <Post ... />;







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 13 '18 at 3:22









                  izb

                  40419




                  40419























                      2














                      You didn't return anything in the map function argument. You can do that easily with a ternary expression and using es6 arrow notation:



                       posts.map(post => (post.id < 2) ? <Post key={post.id} title={post.title} /> : null)





                      share|improve this answer



















                      • 1




                        The ternary expression you used is incorrect. Please check my edit
                        – Hemadri Dasari
                        Nov 13 '18 at 3:44
















                      2














                      You didn't return anything in the map function argument. You can do that easily with a ternary expression and using es6 arrow notation:



                       posts.map(post => (post.id < 2) ? <Post key={post.id} title={post.title} /> : null)





                      share|improve this answer



















                      • 1




                        The ternary expression you used is incorrect. Please check my edit
                        – Hemadri Dasari
                        Nov 13 '18 at 3:44














                      2












                      2








                      2






                      You didn't return anything in the map function argument. You can do that easily with a ternary expression and using es6 arrow notation:



                       posts.map(post => (post.id < 2) ? <Post key={post.id} title={post.title} /> : null)





                      share|improve this answer














                      You didn't return anything in the map function argument. You can do that easily with a ternary expression and using es6 arrow notation:



                       posts.map(post => (post.id < 2) ? <Post key={post.id} title={post.title} /> : null)






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 13 '18 at 3:44









                      Hemadri Dasari

                      7,39411239




                      7,39411239










                      answered Nov 13 '18 at 3:33









                      Riley Steele Parsons

                      23116




                      23116








                      • 1




                        The ternary expression you used is incorrect. Please check my edit
                        – Hemadri Dasari
                        Nov 13 '18 at 3:44














                      • 1




                        The ternary expression you used is incorrect. Please check my edit
                        – Hemadri Dasari
                        Nov 13 '18 at 3:44








                      1




                      1




                      The ternary expression you used is incorrect. Please check my edit
                      – Hemadri Dasari
                      Nov 13 '18 at 3:44




                      The ternary expression you used is incorrect. Please check my edit
                      – Hemadri Dasari
                      Nov 13 '18 at 3:44











                      1














                      The second didn't work because you forgot the return statement.



                      Try this:



                        <>
                      {posts.map(post => {
                      // changes are here
                      if (post.id < 2) {
                      return <Post key={post.id} title={post.title} />; //added return statement
                      }
                      })}
                      </>





                      share|improve this answer


























                        1














                        The second didn't work because you forgot the return statement.



                        Try this:



                          <>
                        {posts.map(post => {
                        // changes are here
                        if (post.id < 2) {
                        return <Post key={post.id} title={post.title} />; //added return statement
                        }
                        })}
                        </>





                        share|improve this answer
























                          1












                          1








                          1






                          The second didn't work because you forgot the return statement.



                          Try this:



                            <>
                          {posts.map(post => {
                          // changes are here
                          if (post.id < 2) {
                          return <Post key={post.id} title={post.title} />; //added return statement
                          }
                          })}
                          </>





                          share|improve this answer












                          The second didn't work because you forgot the return statement.



                          Try this:



                            <>
                          {posts.map(post => {
                          // changes are here
                          if (post.id < 2) {
                          return <Post key={post.id} title={post.title} />; //added return statement
                          }
                          })}
                          </>






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 13 '18 at 3:24









                          Nguyễn Thanh Tú

                          4,6193827




                          4,6193827






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.





                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                              Please pay close attention to the following guidance:


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53273283%2freact-conditional-rendering-inside-component-return-function%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Xamarin.iOS Cant Deploy on Iphone

                              Glorious Revolution

                              Dulmage-Mendelsohn matrix decomposition in Python