Can anyone assist me in setting up automatic method display in a React class component?

Struggling to develop a card for my react-app that contains 5 props holding strings from a Multi-dimensional Json array. Using bootstrap cards to display the information on the Virtual Dom, but facing an issue with showing and hiding text:

{this.props.noticia.titulo}
{this.props.noticia.imagen}
{this.props.noticia.categoria}
{this.props.noticia.parrafo}

To show the prop 'parrafo' when clicked, I utilize a button and collapse functionality, but currently experiencing a problem where the entire page loads showing all the text at once, instead of initially hiding it and then revealing it only upon double-click.

Below is the code snippet in question:

import React from "react";
import "bootstrap/dist/css/bootstrap.css";
import Card from "react-bootstrap/Card";
import { Button, Collapse } from "react-bootstrap";
import { BrowserRouter as Router, Link, Route } from "react-router-dom";

class MovieRow extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      gists: null,
      news: this.props
    };
    this.toggleContent = this.toggleContent.bind(this);
  }

  toggleContent() {
    var coll = document.getElementsByClassName("collapsible");
    var i;

    for (i = 0; i < coll.length; i++) {
      coll[i].addEventListener("click", function() {
        this.classList.toggle("active");
        var content = this.nextElementSibling;
        if (content.style.display === "block") {
          content.style.display = "none";
        } else {
          content.style.display = "block";
        }
      });
    }
  }
  
  render() {
    const gists = this.props;

    return (
      <Router>
        <Card style={{ width: "18rem" }} key={gists.noticia.id}>
          <Card.Img variant="top" src={gists.noticia.imagen} />
          <Card.Body>
            <Card.Title>{gists.noticia.titulo}</Card.Title>
            <Button
              variant="outline-dark"
              className="collapsible"
              onClick={this.toggleContent}
            >
              More Information
            </Button>
            <div className="content">
              <p>{gists.noticia.parrafo}</p>
            </div>
          </Card.Body>
        </Card>
      </Router>
    );
  }
}

export default MovieRow;

Answer №1

Consider implementing the following approach: The state initially sets showParrafo to false. The method dolor() toggles it, while render handles the view logic.

class MovieRow extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      showParrafo: false,
      gists: null,
      news: this.props // <-- why are you doing this?
    };
  }

  dolor() {
    this.setState({
      showParrafo: !this.state.showParrafo
    });
  }

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

    return (
      <div>
        <Button
          variant={"outline-dark"}
          className={"collapsible"}
          onClick={this.dolor.bind(this)}
        >
          More Information
        </Button>

        <div className={"content"}>
          {showParrafo && <p>{this.props.noticia.parrafo}</p>}
        </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

Creating a Node.js API using express and mysql to retrieve various data including record count, page number, and implementing pagination functionality

How can I efficiently retrieve and display total_record_count, page_number, page_size, total_pages, has_more information in the response while implementing pagination given that I am limiting my query to 100 results? What would be the most effective approa ...

What are the steps for running app.js deployed on a remote server using the local bash terminal?

After launching my web application on GoDaddy, which is built in Node.js, I have encountered a dilemma. In order to run app.js, I currently rely on my computer's bash command prompt. However, this poses an issue - if I were to shut down my laptop, the ...

Creating a WordPress Infographic: How to Design a "Wide" Graphic

I have a question for those who are experienced with infographics. I'm in the process of getting an infographic designed for my blog and I've noticed that some websites have a feature that allows the infographic to expand to full width when you c ...

Retrieving the chosen option from a dropdown menu using AngularJS

<tr (click)="onRowClick(myDropDownList.value)"> <td> <select #myDropDownList (click)="$event.stopPropagation()" (change)="onChange($event.target.value)"> <option *ngFor="let n of numbers" [value]="n">{{n}}</option> </se ...

Pushing a React application to the web at username.github.io

I am attempting to deploy a React app at username.github.io Encountering two primary issues: Each time I build and deploy the application with gh-pages, it goes to the gh-pages branch. Github always serves from the master branch when the repository name ...

Centered on the page vertically, two distinct sentences gracefully align without overlapping, effortlessly adjusting to different screen sizes

I had no trouble centering horizontally but I'm struggling with vertical alignment. I want these two sentences to be positioned in the middle of the page, regardless of device size. I attempted using vertical-align without success and then tried posit ...

Dealing with Click Events Outside of a React Component in TypeScript

For my first time using react typescript, I implemented an outside click event. However, I encountered a problem where clicking on the active or selected component triggers both the onclick and outside click events simultaneously. Here is a GIF link to he ...

The flex-basis property seems to be malfunctioning as the image suddenly vanishes when

While my question may seem similar to others, the issue at hand is actually quite different. Here's how it appears in Chrome https://i.sstatic.net/tngvr.jpg Safari https://i.sstatic.net/eE74k.png In Safari, you'll notice that the map disappear ...

Minimize latency in rendering textfield values when binding the onChange event to retrieve values in a React application

Within the interface, there is a TextField component from Material-UI for user input. Additionally, there are two tables on the same page containing numerous values. To capture the input value from the TextField, an onChange event with setState has been im ...

What's the trick to efficiently managing multiple checkboxes in an array state?

I have a lengthy collection of checkboxes that is not well optimized. I am trying to obtain the checked ones and store them in an array state. However, I am uncertain about how to handle this situation and I would appreciate some assistance. It should also ...

``I'm having trouble with Codeigniter's echo and var_dump functions

I'm having trouble with getting var_dump to work in this scenario. The ajax call is successful, but no output is being displayed, not even a simple string from PHP. Here is my controller code: function check_links() { $matches = $this- ...

What is the method to retrieve text from a div element with Webdriver-IO?

Is there a way to extract the value from the following HTML element using Webdriver-IO for automated testing? <div class="metric-value ng-binding" ng-style="{'font-size': vis.params.fontSize+'pt'}" style="font-size: 60 ...

Activate HTML5 video playback one time only

How can I use a script to play an HTML5 video only once when an element is in viewport, and then pause it? When I start scrolling again, the video should resume playing. Any suggestions on how to trigger play just once? Script: jQuery.fn.isInViewport = fu ...

Using Three.js to seamlessly transition from one Panorama Cube to another with a smooth zoom-in effect

As a newcomer to Three.js, I am currently experimenting with an example featuring a set of 6 image cubes for a panorama effect. This allows users to pan, zoom in, and zoom out around the cubes. If you're interested, you can check out the example here ...

Using XSLT with JavaScript

I am currently working with a set of XML files that are linked to XSLT files for rendering as HTML on a web browser. Some of these XML files contain links that would typically trigger an AJAX call to fetch HTML and insert it into a specific DIV element on ...

Utilize data fields beyond the export default in Vue

Is there a way to access the information stored within the export default in my Vue component's JavaScript file? Specifically, I am trying to retrieve the contents of the routes array within the calculateAndDisplayRoute() function. overview.js funct ...

In JavaScript, you can add or replace an object in an array of objects by checking for a specific property

I am looking for a more concise way to add or replace an object within an array. var arr = [ {uid: 1, name: "bla", description: "cucu"}, {uid: 2, name: "smth else", description: "cucarecu"}, ] Here is a new object: var mynewObject = {uid: 1, name: " ...

Position SVG's in relation to one another

I have two SVG's and I'm looking to position the second SVG in the top right corner of the first SVG. In this example, I want to place the exclamation SVG in the TOP RIGHT corner of the first SVG. Can someone provide guidance on what changes I n ...

Utilizing jQuery to execute a consistent action for every element on a webpage

After reading numerous related questions, I have come to the conclusion that none of them seem to address my specific situation. I am looking to add a border around a single element without affecting its parent elements. My attempt with the code below usi ...

The system couldn't locate the module: Issue: Unable to find module 'fs' within the directory

I am currently working on integrating the ADAL JS sample code from this link into a SharePoint framework client web part. My code is fairly straightforward, as I have already installed packages like adal, fs, and node-fs using NPM. However, when running t ...