Home > Enterprise >  Use a random number to render that corresponding object ID's data in React
Use a random number to render that corresponding object ID's data in React

Time:05-23

I'm trying to create an react app where you press a button and it gives you a date night option and a corresponding image. I created a small array of objects within dates.js ex:

export const dates = [
    {
        id: 0,
        name: "Comedy Club",
        image: "/assets/images/comic.jpg",   
    },
    {
        id: 1,
        name:"Piano Bar ",
        image: "/assets/images/piano-bar.jpg",
    }, 

Then I created a GetDates.js to use the random method & corresponding onclick event. Below is where I'm stuck. I've changed this code 100 times based on various previous answers and youtube tutorials but I receive errors or they are not exactly what I'm trying to render. Can you please let me know from this last update what is needed to display the dates.name & dates.image based on the randomId method used below? Again, I've altered this so much from my original attempt that I'm not sure this is the best approach. Any advice would be greatly appreciated!

class GetDates extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      image: "",
    };
  }

  randomSelect() {
    const randomId = dates[Math.floor(Math.random() * dates.length)].id;
    this.setState({ ...this.props.dates[randomId] });
  }

  render() {
    return (
      <div className="results-container">
        <button className="date-btn" onclick={this.randomSelect}>
          GET DATE IDEAS!
        </button>
      </div>
    );
  }
}

export default GetDates;

CodePudding user response:

The prop is called onClick in React, not onclick (like the HTML attribute). You should also render the currently selected item, which you currently do not. In general you should also use functional components instead of class components. Also be careful with this as it may not refer to what you think it does. When you use an array function () => setCurDate() you can be sure that this is bound correctly. I recommend you read the MDN docs for 'this' in order to understand why that is and what you can do to prevent it.

Here a simple implementation tackling all the abovementioned issues.

const dates = [
  {
    id: 0,
    name: "Comedy Club",
    image: "https://dummyimage.com/600x100/000/fff&text=Comedy Club",
  },
  {
    id: 1,
    name: "Piano Bar ",
    image: "https://dummyimage.com/600x100/000/fff&text=Piano Bar",
  },
];

function GetDates() {
  // state for the currently selected item
  const [curDate, setCurDate] = React.useState(randomSelect());

  function randomSelect() {
    // select one item at random (it is possible that the same image is selected more than once in a row)
    const selected = Math.floor(Math.random() * dates.length);
    return dates[selected];
  }

  return (
    <div className="results-container">
      {/* onClick update the state by creating a copy of the object to trigger a state update */}
      <button className="date-btn" onClick={() => setCurDate({...randomSelect()})}>
        GET DATE IDEAS!
      </button>
      {/* Render the currently selected item */}
      <h3>{curDate.name}</h3>
      <img src={curDate.image} />
    </div>
  );
}

ReactDOM.render(<GetDates />, document.getElementById("root"));
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<div id="root"></div>

CodePudding user response:

If you're getting an error upon clicking the button, then it might be due to the randomSelect method not being bound to the class.

Try adding the bind call in your constructor, so you would have:

constructor(props) {
    ...

    this.randomSelect = this.randomSelect.bind(this);
}

You can read more on this here: https://reactjs.org/docs/handling-events.html

  • Related