Home > Software design >  React js - Dynamically Change the style Maxheight of element based on dynamic content
React js - Dynamically Change the style Maxheight of element based on dynamic content

Time:03-09

I have a requirement that need to update the style of the element based on dynamic content. Here i am setting ul element max height based on detail content.

if (element.innerText === this.res.viewMore) {
      primaryButtonText = this.res.viewLess;
      messageListElement.style.maxHeight = `${this.checkHeightOfList(
        detail.split(','),
      )}px`;
    } else {
      primaryButtonText = this.res.viewMore;
      messageListElement.style.maxHeight = null;
    }

What is the best practice to update the max height in react js ? Here is my DOM

CodePudding user response:

The best practice to update a style attribute in react is to do something like this:

const maxHeight = someCondition ? null : '100px';

And to apply this max height, do:

<div style={{max-height: maxHeight}}>my list</div>

If you want the max-height to dynamically update, store maxHeight as a state variable and update it accordingly using setState.

CodePudding user response:

Your example code has a strong javascript approach. In React you would store your state in a variable (viewState in my example), and you render styling conditionally with this variable. Your code could look something like this:

const yourDetailArray = ["foo", "bar", "test", "view"];
    
const List = () => {
  const [viewState, setViewState] = React.useState(false);

  const checkHeightOfList = () => {
    // Setting the max height to 10px * length of array to show effect
    if (viewState) return yourDetailArray.length * 10   "px";
    else return null;
  };

  return (
    <React.Fragment>
      <ul style={{ maxHeight: checkHeightOfList(), border: "1px solid grey" }}>
        {yourDetailArray.map((item) => (
          <li>{item}</li>
        ))}
      </ul>

      <button onClick={() => setViewState(!viewState)}>
        {viewState ? "View less" : "View more"}
      </button>


      <p>State is currently : {viewState ? "true" : "false"}</p>
      <p>Max height is currently:  { checkHeightOfList() || 'null' }</p>
    </React.Fragment>
  );
};

    // Render it
    ReactDOM.render(
      <List />,
      document.body
    );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>

There are ways to optimise this code, but hopefully it shows the concept. Please note that this example is using functional components which might differ in your code.

  • Related