ReactJS: setTimeout() not working inside return?

Inside of render(), return(), I am trying to set a timeout but it’s not working.

Am I doing something wrong?

{setTimeout(() => {
          filtered.length && (
            <FilterListContainer
              containerHeight={this.state.filterContainerHeight}
            >
              <FilterListScroll>
                <FilterList ref={this.filterListRef}>
                  {filtered.map((k) => (
                    <SidebarFilter
                      key={k}
                      type={k}
                      filter={this.props.body_search_filter[k]}
                      handleChange={this.handleFilterChange}
                    />
                  ))}
                </FilterList>
              </FilterListScroll>
            </FilterListContainer>
          );
        }, 1)}

>Solution :

You’ve said you don’t want that content to appear until "a bit later."

To do that, you’d want to have a state member saying whether to show the content, use that when rendering, and have the setTimeout that changes the state member’s value.

For instance, here’s an example using hooks:

const { useState, useEffect } = React;

const Example = () => {
    const [showList, setShowList] = useState(false);
    
    useEffect(() => {
        const handle = setTimeout(() => {
            setShowList(true);
        }, 800); // Longer delay so you can see it
    }, []);
    
    return <div>
        <div>Hi there</div>
        {showList && <div>This is the list</div>}
    </div>;
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Example />);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.0.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.0/umd/react-dom.development.js"></script>

Leave a Reply