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

Keep action from function after re-render – React

Context : I have a side bar, and multiple links in it. For example, if I click on User, the main page will load datas from users and display in a table. If I click on Addresses, same with all addresses.

What I want to do : I want to set a substring on all spans with a length > 30, so the table is not too long when I receive a long description for example.

My code : I created a Layout component as container for my App component like this :

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

function MyApp({ Component, pageProps }: AppProps) {
  return(
    <Layout>
      <Component {...pageProps} />;
    </Layout>
  )
}

And I apply my logic for substring in my layout component :

function Layout(props) {
  
  const subString = (spansList) => {
    for (const s of spansList) {
      if (s.textContent.length > 30) {
        return s.textContent = s.textContent.substring(0, 30) + "..."
      }
    }
  }
  
  const allWithClass = Array.from(
    document.getElementsByClassName('MuiTypography-body2')
  );
  
  useEffect(() => {

    subString(allWithClass)
  
  }, [allWithClass])

  return (
[...]

My problem : This code works, but when I re-render by clicking on an other menu in my sidebar, the function subString is no longer applied.

I don’t now how to make it persistent.

Thank you for your time

>Solution :

I think what you need is a state which changes depending on the link you click on it, and set this state as a dependence to the useEffect hook, so when you click other link the useEffect hook re-execute

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