1

I have this component:

import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import PropTypes from 'prop-types';
import './cardCheck.css';

@inject('auto')
@observer
class CardCheck extends Component {
  render() {
    const { auto } = this.props;

    return (
      <div>
        <div className="newsletter-container">
          <h1>Enter the ID of your card:</h1>
          <div className="center">
            <input type="number" />
            <input type="submit" value="Check" onClick={event => {displayInfo}} />
          </div>
          <div className="results"></div>
        </div>
        <h1>Offers:</h1>
      </div>
    );
  }
}

CardCheck.propTypes = {
  auto: PropTypes.shape({
    carCount: PropTypes.number
  })
};

CardCheck.wrappedComponent.defaultProps = {
  auto: autoPropTypeDefaults
};

export default CardCheck;

I want to make so that when someone clicks the input with value Check the div below with the className of results to be populated with my data from the store:

import { observable, action, computed } from 'mobx';

class Auto {
  @observable
  auto = [
    {
      name: 'Shop1'
    },
    {
      name: 'Shop2'
    }
  ];

  @action
  displayInfo() {

  }

}

export { Auto };

I tried to make the displayInfo function iterate through the array with objects with a map from loadash but it didn't work, it did not displayed the data inside the div, how can I do this?

Peter Johnson
  • 39
  • 1
  • 3

1 Answers1

0

You can add an observable field on your CardCheck component that you toggle with the onClick event handler, and when the field is true you can display all entries in the auto array.

Example

class CardCheck extends Component {
  @observable
  checked = false;

  onClick = event => {
    event.preventDefault();
    this.checked = !this.checked;
  };

  render() {
    const { auto } = this.props;

    return (
      <div>
        <div className="newsletter-container">
          <h1>Enter the ID of your card:</h1>
          <div className="center">
            <input type="number" />
            <input type="submit" value="Check" onClick={this.onClick} />
          </div>
          <div className="results">
            {this.checked &&
              auto.auto.map((a, index) => <div key={index}>{a.name}</div>)}
          </div>
        </div>
        <h1>Offers:</h1>
      </div>
    );
  }
}
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • I tried but it blows up with this error: 25:91 error Do not use Array index in keys react/no-array-index-key – Peter Johnson Aug 04 '18 at 14:06
  • @PeterJohnson Alright. That looks like a linter error, not a MobX error. If you know that the `auto` names will be unique, you can use `key={a.name}` instead, or you could add a unique `id` property to your elements in the `auto` array and use that as `key`. – Tholle Aug 04 '18 at 14:08