Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot receive to get clicked button value in React.js

I tried to get the button value when I click the button (onClick method).

I tried to do generally the way that is e.target.value but sometimes it returns an undefined or empty string. Even I tried to arrow function way that I find in here but still doesn’t work. Could you help me with this problem? Which part is wrong or do I miss something?

This is the main part of my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

updateProducts = e => {
    // e.preventDefault();
    let buttonValue = e.target.value;
    console.log(buttonValue);
    fetch('/data/MainProductsShoes.json', {})
      .then(res => res.json())
      .then(data => {
        this.setState({
          productsInfo: data,
          // category_id: '',
        });
      });
};

and

<main className="contentsBody">
            <div className="contentsLink">
              <div className="viewAll">
                <button onClick={this.updateProducts} value="viewAll">
                  <span>전체보기</span>
                </button>
              </div>
              <div className="Shoes">
                <button onClick={this.updateProducts} value="shoes">
                  <span>신발</span>
                </button>
              </div>
              <div className="Clothes">
                <button onClick={this.updateProducts} title="clothing">
                  <span>의류</span>
                </button>
              </div>
              <div className="Supplies">
                <button onClick={this.updateProducts} title="acc">
                  <span>용품</span>
                </button>
              </div>
            </div>

Here’s the complete code:

import React, { Component } from 'react';
import './Main.scss';
import COLOR_LISTS from './colorList';
import Products from './ProductsInfo/Products';

export class Main extends Component {
  constructor() {
    super();
    this.state = {
      productsInfo: [],
    };
  }
  // const API = "DASDDADDAD" => 컴포넌트 마다 다 적용할수x
  componentDidMount() {
    fetch('/data/MainProducts.json', {})
      .then(res => res.json())
      .then(data => {
        this.setState({
          productsInfo: data,
        });
      });
  }

  updateProducts = e => {
    // e.preventDefault();
    let buttonValue = e.target.value;
    console.log(buttonValue);
    fetch('/data/MainProductsShoes.json', {})
      .then(res => res.json())
      .then(data => {
        this.setState({
          productsInfo: data,
          // category_id: '',
        });
      });
  };

  // updateProducts = () => {
  //   console.log('clicked');
  //   fetch('/data/MainProducts.json', {
  //     method: 'GET',
  //   })
  //     .then(res => res.json())
  //     .then(data => {
  //       this.setState({
  //         productsInfo: data,
  //         category_id: this.state.category_id,
  //       });
  //     });
  // };

  // showToProductDetailPage = () => {
  //   const { productsInfo } = this.state;
  //   productsInfo &&
  //     productsInfo.map((product, idx) => (
  //       <Products key={idx} productInfo={product} />
  //     ));
  // };

  render() {
    const { productsInfo } = this.state;

    return (
      <div className="MainWrapper">
        <div className="sectionHeader">
          <div className="sectionTitle">
            <div className="sectionTitleCategory">
              <span className="categoryName">Men</span>
              <br />
              <br />
              <span>Men's 의류(12)</span>
            </div>

            <div className="sectionControl">
              <button>필터</button>
              <select name="list" className="productsFilter">
                <option value="newestOrdeer">신상품순</option>
                <option value="hightCostoOder">높은가격순</option>
                <option value="lowCostOrder">낮은가격순</option>
              </select>
            </div>
          </div>
        </div>

        <div className="contentsWrapper">
          <aside className="contentsSide">
            <div className="HorizontalLine" />
            <div className="colors">
              <span>색상</span>
              <ul className="colorLists">
                {COLOR_LISTS.map((color, idx) => {
                  return (
                    <li className="colorLayout" title="베이지" key={idx}>
                      <input type="checkbox" />
                      <label
                        className="checkboxLabel"
                        for="checkbox"
                        style={{ backgroundColor: color.colorProps }}
                      />
                      <span className="productColor">{color.color_name}</span>
                    </li>
                  );
                })}
              </ul>
            </div>
            <div className="sizes">
              <div className="HorizontalLine" />
              <span>사이즈</span>
              <div className="sizeLists">
                <button title="230">230</button>
                <button title="230">235</button>
                <button title="230">240</button>
                <button title="230">245</button>
                <button title="230">250</button>
                <button title="230">255</button>
                <button title="230">260</button>
                <button title="230">265</button>
                <button title="230">270</button>
                <button title="230">275</button>
                <button title="230">280</button>
              </div>
              <div className="HorizontalLine" />
            </div>
          </aside>

          <main className="contentsBody">
            <div className="contentsLink">
              <div className="viewAll">
                <button onClick={this.updateProducts} value="viewAll">
                  <span>전체보기</span>
                </button>
              </div>
              <div className="Shoes">
                <button onClick={this.updateProducts} value="shoes">
                  <span>신발</span>
                </button>
              </div>
              <div className="Clothes">
                <button onClick={this.updateProducts} title="clothing">
                  <span>의류</span>
                </button>
              </div>
              <div className="Supplies">
                <button onClick={this.updateProducts} title="acc">
                  <span>용품</span>
                </button>
              </div>
            </div>
            <article className="productsMapping">
              {productsInfo &&
                productsInfo.map((product, idx) => (
                  <Products key={idx} productInfo={product} />
                ))}
            </article>
          </main>
        </div>
      </div>
    );
  }
}

export default Main;

>Solution :

change you updateProducts function to receive a string value representing the product name:

updateProducts = (name) => {
    console.log(name);
    fetch('/data/MainProductsShoes.json', {})
      .then(res => res.json())
      .then(data => {
        this.setState({
          productsInfo: data,
          // category_id: '',
        });
      });
  };

Then on each button pass the product name as an argument:

<button onClick={() => this.updateProducts('shoes')}>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading