Home  >  Q&A  >  body text

Does Next.js support conditional rendering and pre-rendering of unrendered HTML?

<p>Next.js pre-renders HTML on a page that only displays when a certain button is clicked? For example, when we have tabs, does it render the content of the tab that is not yet shown? </p>
P粉450744515P粉450744515455 days ago530

reply all(1)I'll reply

  • P粉011684326

    P粉0116843262023-08-15 13:57:52

    Not only for Next.js, but also for React, it will depend on how you show/hide the component conditionally, especially if it is hidden by CSS or JavaScript. Here is an example:

    // 1. 返回一个空片段或组件
    const Component1 = ({ isVisible }) => {
      if (!isVisible) return <></>;
      return (
        <div>Hello World</div>
      )
    }
    
    // 2. 改变display属性
    const Component2 = ({ isVisible }) => {
      const display = isVisible ? "flex" : "hidden";
      return (
        <div style={{ display }}>Hello World</div>
      )
    }
    
    1. In the first example, when the isVisible property is set to false, an empty fragment will be rendered. An empty fragment will not produce any HTML.

    2. In the second example, we just changed the display property of the CSS based on the attribute, and the generated HTML will still be included in your HTML without being visible.

    reply
    0
  • Cancelreply