1

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

thank you for your idea ! How can I store in a useState the current location, since react returns "window is not defined" ?
@Joh Why do you want to store the window.location, do you use a server-side rendering framework, like next.js for example?
yes I'm using Next.js. window.location is the way I usualy use to get URL
@Joh window should be defined on the useEffect hook.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.