N
N
nivaech2018-12-29 19:13:20
JavaScript
nivaech, 2018-12-29 19:13:20

How to change the style of all elements of a class in React?

There are many product cards. By pressing the button, the grid should be compacted so that more elements are displayed, and for this I want to change the size of the cards on click. Tried this option:

function clickSmaller() {
        const element = document.getElementsByClassName('product-card');
            element.style.width = "250px";   
            element.style.height= "300px";

But in this case, React throws an error, but does what it needs to do if you set the position number in the class array (for example,
document.getElementsByClassName('product-card')[0], in this case, only the first object's height and width parameters are changed). I also tried the addClass method, in which a class with the necessary parameters would simply be added, but this is also a bug.
function clickSmaller() {
        const productCards = document.getElementsByClassName('product-card');
        productCards.classList.add('smallCard')
        }

How can I change the style settings of all class elements?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-12-29
@nivaech

Avoid using direct access to DOM elements in React development and use component state.

const Grid extends React.Component {
  state = { itemsSize: 'sm' };

  handleChangeSize = () => { /* some code */ };  

  render() {
    const { itemSize } = this.state;
    const { items } = this.props;

    return (
      <Wrapper>
        <ControlPanel onChangeSize={this.handleChangeSize} />
        {items.map(item => <Item key={item.id} size={this.state.itemSize} />)}
      </Wrapper>
    );
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question