Home > database >  Line wrapping does not work when element width is set from code
Line wrapping does not work when element width is set from code

Time:01-05

In my React app, one of the components gets its width value in props from the parent. I set the width with:

myComponentRef.current.setAttribute('style', 'width:'   props.width   'px')

I also tried doing it like this:

myComponentRef.current.style.width = props.width   "px"

In this case, my component takes the width according to the width of the text that is about it. The text does not wrap to the next line. If I specify the width in css style, then everything works as it should. And the text is transferred. And when setting the width from the component code, it does not work. Please help me figure out what's wrong.

CodePudding user response:

There could be a few reasons why setting the width of your component through js is not working as expected. You could try these to solve:

  1. Make sure that myComponentRef.current is actually referring to the DOM element that you want to modify. You can check this by adding a console.log to see the value of myComponentRef.current.

  2. Make sure that props.width is a valid value for the width of your component.

  3. Make sure that you are correctly setting the style attribute of your component. One another way is to use it like this:

myComponentRef.current.style = { width: props.width "px" };

  1. Make sure that you are not overwriting the style attribute of your component anywhere else in your code.

CodePudding user response:

It turned out that the reason is quite stupid. It was really a matter of overwriting the style, but not with another css class, but with another call to the setAttribute() function

I did not know that such functions overwrite each other, leaving only what is written in the class. If for example:

myComponentRef.current.setAttribute('style', 'width:'   props.width   'px')

And after that I do:

myComponentRef.current.setAttribute('style', 'height:'   props.height   'px')

The Width value that I set earlier will disappear. After each call to such a function, the element retains only those styles that are in the class and those that were assigned by the last call to setAttribute() (of course this also applies to other ways to assign a style)

Now to assign both styles I have to write:

myComponentRef.current.setAttribute('style', 'width:'   props.width   'px; height:'   props.height   'px')

And if the call to this function is repeated while the program is running, for example, my window opens and closes. I have every time when opening and closing the window (changing the height) add the width to the same place so that it remains unchanged.

P.S. - For me, the problem was solved much easier by creating a container for my component with comments. I wrapped the comments in this container in the parent component and gave the container the required width using inline

  • Related