Home > Back-end >  Keep action from function after re-render - React
Keep action from function after re-render - React

Time:10-11

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 :

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

CodePudding user response:

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

  • Related