Clicking on React opens the full picture

I'm encountering an issue in my react project where the pictures I fetch from a JSON file don't open in full screen when clicked individually. Instead, they all open at once. As a newcomer to React, I suspect that my current approach might be incorrect. Here is the code snippet:

import React from "react";
import axios from "axios";
import Card from "@material-ui/core/Card";
import CardActionArea from "@material-ui/core/CardActionArea";
import CardContent from "@material-ui/core/CardContent";
import CardMedia from "@material-ui/core/CardMedia";
import Typography from "@material-ui/core/Typography";
import "../App.scss";

export default class Portfolio extends React.Component {
  state = {
    persons: [],
  };
  handleShowDialog = () => {
    this.setState({ isOpen: !this.state.isOpen });
    console.log("cliked");
  };
  
  componentDidMount() {
    axios.get("http://localhost:3000/persons.json").then((res) => {
      const persons = res.data;
      this.setState({ persons });
    });
  }
  render() {
    
    return (
      <div className="container">
        <div className="row justify-content-center">
          {this.state.persons.map((person) => (
            <Card key={person.id} className="col-3 axios-items">
              <CardActionArea>
                <CardMedia
                  component="img"
                  alt={person.alt}
                  height="140"
                  image={person.src}
                  title={person.title}
                  onClick={this.handleShowDialog}
                />
                {this.state.isOpen && (
                  <dialog
                    className="dialog"
                    style={{ position: "absolute" }}
                    open
                    onClick={this.handleShowDialog}
                  >
                    <img
                      className="image"
                      src={person.src}
                      onClick={this.handleShowDialog}
                      alt="no image"
                    />
                  </dialog>
                )}
                <CardContent>
                  <Typography gutterBottom variant="h5" component="h2">
                    {person.title}
                  </Typography>
                  <Typography
                    variant="body2"
                    color="textSecondary"
                    component="p"
                  >
                    {person.desc}
                  </Typography>
                </CardContent>
              </CardActionArea>
            </Card>
          ))}
        </div>
      </div>
    );
  }
}

Answer №1

Consider utilizing a different state as well.

import React from "react";
import axios from "axios";
import Card from "@material-ui/core/Card";
import CardActionArea from "@material-ui/core/CardActionArea";
import CardContent from "@material-ui/core/CardContent";
import CardMedia from "@material-ui/core/CardMedia";
import Typography from "@material-ui/core/Typography";
import "../App.scss";

export default class Portfolio extends React.Component {
  state = {
    people: [],
  };
  handleShowModal = (id) => {
    this.setState({ ...this.state, selectedId: id, showModal: true });
    console.log("clicked");
  };
  handleHideModal = () => {
    this.setState({ ...this.state, showModal: false });
    console.log("closed");
  };

  componentDidMount() {
    axios.get("http://localhost:3000/people.json").then((res) => {
      const people = res.data;
      this.setState({ people });
    });
  }
  
  render() {
    return (
      <div className="container">
        <div className="row justify-content-center">
          {this.state.people.map((person) => (
            <Card key={person.id} className="col-3 axios-items">
              <CardActionArea>
                <CardMedia
                  component="img"
                  alt={person.alt}
                  height="140"
                  image={person.src}
                  title={person.title}
                  onClick={()=>{this.handleShowDialog(person.id)}}
                />
                {(this.state.showModal&&this.state.selectedId === person.id) && (
                  <dialog
                    className="dialog"
                    style={{ position: "absolute" }}
                    open
                    onClick={this.handleHideDialog}
                  >
                    <img
                      className="image"
                      src={person.src}
                      onClick={this.handleShowDialog}
                      alt="no image"
                    />
                  </dialog>
                )}
                <CardContent>
                  <Typography gutterBottom variant="h5" component="h2">
                    {person.title}
                  </Typography>
                  <Typography
                    variant="body2"
                    color="textSecondary"
                    component="p"
                  >
                    {person.desc}
                  </Typography>
                </CardContent>
              </CardActionArea>
            </Card>
          ))}
        </div>
      </div>
    );
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Parsing JSON data returned from ASP.NET in JavaScript is proving to be problematic

After successfully converting a DataSet to JSON using a jQuery AJAX call, everything seems fine. The response I get back is as follows: {"Table":[[2,"BlackBerry Tour","2013-09-10","2013-09-13","Project"],null]} The JSON response looks valid and even pass ...

"Optimizing npm packages for front-end web development in vanilla JavaScript: A guide to bundling for production deployments on

My website is built using vanilla HTML/CSS/JavaScript with ES6 modules and can be deployed to GitHub pages and Netlify. I have set up my site by importing "main.js" in my HTML like this: <script src="js/main.js" type="module" defer&g ...

How to Grow Your Business from a Single Vertical: Strategies for Diversifying

Is there a way to specify which column a table row should expand from when using expandedRowRender to expand table rows on click? For example, can we make the rows expand from column 2 onwards? columns = [ { title: "Name", dataIndex: "name", }, ...

Problem with jQueryUI Sortable cancel property preventing input editing

Currently, I am utilizing jquery-3.2.1.min.js and jquery-ui.min.js version 1.12.1 The task at hand is to create a sortable list where certain elements are not sortable (specifically, other sortable lists). It is crucial that the input elements remain edit ...

What is the best jQuery library to add to my website?

I have included several jQuery scripts on my website for various functionalities such as sticky header, anchors, and animations. I am wondering if it is necessary to include all of them or if I can just include one or two? Here are the jQuery scripts I ha ...

Organizing Files and Creating Applications with Electron

Recently, I came across Electron and found it to be a fantastic tool for developing desktop applications. I created a basic Twitter Aggregator that functions when I execute nodemon app.js. Now, I want to package it with Atom in order to run it in its own w ...

Having issues passing parameters with Ajax, Python Bottle, Jquery, and JSON collaboration

Every time I make an AJAX request POST, the newUser() function seems to be ignoring any arguments being passed even though I have filled out both userInput and passInput fields. Here's the JS/JQ/AJAX code snippet: var userInput = document ...

Arrange radio buttons vertically in a table

I am attempting to display a vertical list of radio buttons within a table cell. Is this achievable? Here is the code snippet I am currently working with: <table> <tr> <td> First Name </td> ...

Significance of utilizing the react-router-redux push feature

I have been incorporating react-router-redux push in my project, but I am unsure as to why my team has chosen to include it in actionsToProps. Is there a particular benefit that comes from this setup? Using push in actionsToProps seems to be working fine. ...

Struggling to connect to an express route?

I'm currently working on a MERN project and I'm encountering a small issue. When trying to make a POST request to a specific route, Express throws a 404 error and tells me that it can't find the desired route. However, everything works perfe ...

What is the method for determining the level based on the provided experience points?

I've created a formula that can calculate experience based on specific levels and another formula that calculates the level based on given experience. However, there seems to be an issue with the second function as it is not returning the expected val ...

Combine the date and time into one variable

Is there a way to save the date and time fields in a variable with the format: 0000-00-00T00:00:00.000Z? component.html <mat-form-field appearance="outline" class="pr-sm-8" fxFlex="50"> <mat-label>Fecha Inicio ...

Is it possible to use NextJS to simultaneously build multiple projects and export them as static sites?

I'm currently working on a small Next.js project where I retrieve data from various API endpoints. These endpoints typically follow this format: https://enpoint.com/some-query/project1 The interesting thing about the API is that it can return differe ...

Converting an array of images into blob format and displaying it using PHP

I am attempting to convert an array of images into blob format and then send it to a PHP script for data processing. However, I am encountering an issue where the array of blobs is not being sent correctly, and I am unsure why this is happening. Here is my ...

Guide to combining a React frontend with an independent PHP REST API backend

I successfully created a website with separate front and back ends. The front end is developed using REACT.JS, while the REST API service on the back end is written in PHP with slim 3. All communication between the two ends occurs through JSON, with React ...

Despite importing jQuery, the variable '$' cannot be located

Whenever I try to click the button labeled test, it doesn't do anything. However, an error message appears in the console debug indicating: Error: Unable to locate variable '$'. I suspect this might be a jQuery issue, even though I' ...

In the game of rock paper scissors, the icons become unclickable once you achieve a score of 5

I have created a Rock Paper Scissors game where the score resets if either the user or computer reaches 5 points, but I want to prevent any further play after hitting 5. Currently, the game displays a message and reloads after 5 seconds, during which tim ...

Retrieve data from JSON using jQuery without employing a forEach loop

Here is a JSON string that I have discovered: { "Msg1": "message 1", "Msg2": "message 3", "Msg3": "message 2" } Currently, I am utilizing the following code: function GetMessages(msg) { $.getJSON("./jquery/sample.json", function (result) { $.e ...

It's time to launch my Node.js app - but wait, express.createServer() is no longer supported!

I recently downloaded a Node app to experiment with, and after researching, I found that Express is considered a bit outdated. Can anyone assist me in fixing the code implementation? Here is the code snippet: /** * Module dependencies. */ // base depe ...

What are some strategies for creating a recursive function in JavaScript that avoids exceeding the maximum call stack size error?

I need assistance creating a walking robot function in JavaScript, but I am encountering a call stack size error. function walk(meter) { if(meter < 0) { count = 0; } else if(meter <= 2) { count = meter; ...