Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading