0

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;
2
  • Can you post what error you are getting, or what it is incorrectly rendering? Commented May 22, 2022 at 16:15
  • Hello. In this instance the button/onclick is not functioning. I Commented May 22, 2022 at 16:21

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

This is very close. Do you know what would be causing the images to render as a broken thumbnail? (The only eidt I did was remove react from in front of use state and instead imported useState from react since it was stating that react wasn't defined when using your provided code. The functionality is now working but the image is not rendering correctly.
Yes, usually you would use import ... but that does not work on StackOverflow. You need to make sure the images exist at those paths. So make sure /assets/images/comic.jpg is correct.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.