Home > OS >  fire useEffect on page loaded - react
fire useEffect on page loaded - react

Time:11-10

I work with react-admin (so my content is feteched from my API) and I created a button to minimize the text lenght, so that my table cells does not have a big height, and keep an easy to read table.

not minimized text

minimized text

Here is my code :

const [isMinimized, setIsMinimized] = useState(false);

useEffect(() => {

        if (isMinimized) {
            // reduce texts size
            const spans = document.getElementsByClassName("MuiTypography-body2");
            const spansList = [...spans];
            for (const span of spansList) {
                if (span.textContent.length > 20) {
                    span.textContent = span.textContent.substring(0, 20)   "..."
                }
            }
        }

    }, [isMinimized]);

I trigger this function with a state that change when I click on my button "minimize content".

Now, I'd like to apply this function but when the page is mounted. Not on click event. I want to get rid of the button.

So I tried to set my isMinimized state to true, and apply my useEffect when it is true but on first page load, it does not work.

Any idea how to achieve this ?

PS : It does not work on page load, but if I go to another component, and come back, it works. So I'd like to apply my useEffect on first page load

CodePudding user response:

My understanding is that you want to minimize the cells on page load and get rid of the minimize button all together.

You can achieve this by simply passing an empty array to the dependency array like so:

useEffect(() => {

  // reduce texts size
  const spans = document.getElementsByClassName("MuiTypography-body2");
  const spansList = [...spans];
  for (const span of spansList) {
    if (span.textContent.length > 20) {
      span.textContent = span.textContent.substring(0, 20)   "..."
    }
  }

}, []);

Passing an empty dependency array will let the function passed to useEffect run on the first render, hence eliminating the need for a state variable.

Alternatively, an easier method to achieve the same result would be to use the CSS Text Overflow ellipsis property to truncate strings while still preserving content like so:

.truncate {
  width: 100px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

More info on this here

  • Related