How to run a Javascript function after loading the DOM using React Hooks?

Asked

Viewed 103 times

0

I need to create several li tags based on an array and then insert them into a div, however I need to wait for that div to be created before doing so. Since React doesn’t have Domcontentloaded what can I use to do the same effect? I’m working with React Hooks

  • I did not understand very well you have the example of the code in React?

  • My answer came true?

1 answer

1


From what I could understand, it is necessary to execute some function when the component is ready (charged), utilize useEffect with a array no position, this means execution after loading the component, example:

function App() {
  const [list, setList] = React.useState([
    {id: 1, name: 'name 1'},{id: 2, name: 'name 2'},
    {id: 3, name: 'name 3'},{id: 4, name: 'name 4'}
  ]);
  function init() {
    console.log('carregou ...');
  }
  React.useEffect(() => {
    init();
  },[]);
  return (
    <div>
      <ul>
        {list && list.map((l,x) => (<li key={x}>{l.name}</li>))}
      </ul>
    </div>
  )
}
ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

  • Perfect was that right, can I use it attached to a div? As soon as a div is rendered the useEffect call a function?

  • You can do yes @Jhonatasflordesousa needs to exemplify how you want it, open another question and explain it all as clearly as possible because every doubt generates a new question

Browser other questions tagged

You are not signed in. Login or sign up in order to post.