Arranging Images, Buttons, and Text Vertically in React with CSS

https://i.sstatic.net/0WaeI.png

In my current application, whenever the button is clicked, a random image is generated but it results in everything appearing bunched up. I would like the images, which are of different sizes, to be displayed with the dog's name centered below each one, followed by the button.

Code

import * as React from "react";
import { render } from "react-dom";
import axios from "axios";
import "./styles.css";

function App() {

  const [images, setImage] = React.useState("");
  const [text, setText]    = React.useState("");

  function btnClick() {

    axios
        .all([axios.get("https://dog.ceo/api/breeds/image/random"), 
              axios.get("https://dog.ceo/api/breeds/list/all")
         ]) 
        .then(axios.spread((response) => {
              setImage(response.data.message);
              setText(response.data.message.split('/')[4]);
         }))     
        .catch(err => {
            console.log("Error happened during fetching!", err);
        });
  }

  return (
    <div className = "App">
      <img    className = "Img"    src={images} alt="broken"/>
      <button className = "Button" onClick = {btnClick}>Doggie!</button>
      <strong>{text}</strong>
    </div>
  );
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

CSS

.App {
  font-family: sans-serif;
  text-align: center;
}

.Button {
  display: flex;
}

.Img {
  max-width:100%;
  height:auto;
  max-height:100%;
}

Answer №1

To resolve the issue, try reorganizing the element by enclosing the name within <p></p> tags to ensure it displays on a new paragraph.

import React from "react";
import axios from "axios";
import "./styles.css";

export default function App() {
  const [images, setImage] = React.useState("");
  const [text, setText] = React.useState("");

  function btnClick() {
    axios
    .all([
      axios.get("https://dog.ceo/api/breeds/image/random"),
      axios.get("https://dog.ceo/api/breeds/list/all")
    ])
    .then(
      axios.spread(response => {
        setImage(response.data.message);
        setText(response.data.message.split("/")[4]);
      })
    )
    .catch(err => {
      console.log("Error occurred while fetching data!", err);
    });
 }

 return (
   <div className="App">
    <img src={images} alt="broken" />
    <p><strong>{text}</strong></p>
    <button className="button" onClick={btnClick}>
     Doggie!
    </button>
   </div>
 );
}

Answer №2

To improve the layout of your elements, consider rearranging them as follows:

<img/> <strong/> <button />
.

Also, ensure that any elements originally set to display inline are changed to display as block in your CSS.

Take a look at the snippet provided below for reference. Please note: React has been excluded from this example as it is not relevant to the issue at hand, so disregard the use of class.


<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.App {
  font-family: sans-serif;
  text-align: center;
}

.App strong {
  display: block;
}

.Button {
  width: 100%;
  text-align: center;
}

.Img {
  max-width:100%;
  height:auto;
  max-height:100%;
  display: block;
}
<div class="App">
  <img class="Img" src="https://i.sstatic.net/0WaeI.png" alt="broken"/>
  <strong>{text}</strong>
  <button class="Button" onClick={btnClick}>Doggie!</button>
</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

Retrieving information within a loop through the utilization of a left join操作。

Presently, I am utilizing a while loop to fetch user comments from a MySQL table and applying a conditional class to the buttons within the comment div. Each comment contains two buttons: thumbsup button thumbsdown button I aim to assign the class name ...

Attempting to display images from a markdown file using ReactJS

Trying to display a Markdown file in my React app is giving me some trouble. I am utilizing the react-markdown library and converting the MD to text using the code snippet below: useEffect(() => { fetch(markdownfile).then((response) => re ...

JavaScript program that continuously reads and retrieves the most recent data from a dynamically updating JSON file at regular intervals of every few seconds

I am a beginner in JavaScript and I'm facing an issue with displaying the most recent values from a .json file on an HTML page. The file is updated every 10 seconds, and I am also reading it every 10 seconds, but I'm not getting the latest data. ...

Determine in React whether a JSX Element is a descendant of a specific class

I am currently working with TypeScript and need to determine if a JSX.Element instance is a subclass of another React component. For instance, if I have a Vehicle component and a Car component that extends it, then when given a JSX.Element generated from ...

Vertical alignment of divs in a single column will not be consistent

I need assistance with my website's "team" section. I am trying to ensure that the member_body divs within the same column as the member img and member header can be adjusted in width. However, they are not aligning vertically or maintaining the same ...

Heroku experiencing difficulty loading JavaScript files within a Django application

After attempting to deploy my Django app on Heroku, I encountered an issue. Everything seems to be working when I use "heroku open", but certain buttons and glyphicons are not functioning correctly. The JavaScript files and Bootstrap CDN JS files are not l ...

Implement Vue.js functionality to dynamically add the 'active' class upon clicking an element, while also removing

Is it possible to create an active link on a div element? Check out this example to see how you can achieve that in your code: http://jsfiddle.net/fiddleyetu/9ff79/ $(function() { $( 'ul.nav li' ).on( 'click', function() { $ ...

Concealing rows with empty cells in column E

As someone who is fairly new to incorporating scripts in Google Sheets, I stumbled upon this straightforward and beneficial code snippet online. My objective is to conceal rows within a specified range (rows 10 - 34) where there are blank cells in column E ...

Trouble with Bootstrap popover functionality

Twitter bootstrap-2.3.2 popover is being utilized in my BackboneJs project. When I click, a function is triggered to open the popover: <li> <a class="candidPopover" href="#" id="loginUser" rel="popover"><%= candidateName %></a> & ...

Utilizing REACT to extract values from deeply nested JSON structures

Currently, I am utilizing react to display information from properties stored in a nested JSON. While I can successfully render properties like 'name' and 'id' that are not nested, I encounter an issue when trying to access a nested pro ...

Personalized information boxes for particular data points within highcharts

When hovering over specific points, I want to display unique warnings or explanations in the tooltip. I have included custom text like 'WARNING' and 'WARNING 2' within the series data but am struggling to retrieve that data for each too ...

Issue encountered with the carousel plugin while transitioning to a different page (utilizing Durandal)

I am currently working on a project using the Durandal SPA template, and I have integrated a carousel element into my page: var compositionComplete = function () { $('.testimonials-carousel').carousel({ namespace: "mr-rotato" // ...

Choosing CSS/JS selector: Pick the final element with a class that does not match

My goal is to extract the most recent td element from the latest tr within an HTML table, ensuring that the latest td does not belong to the disabled class. I am attempting to achieve this using pure JavaScript with CSS selectors (without relying on jQuer ...

How can I determine whether the user is being directed to a component with state being navigated to navigate('/tsaks/updateTask', { state: {task: data})

I have a component that displays a list of tasks. When the user clicks on a task, they are redirected to /tasks/updateTask along with the task data. navigate('/tasks/updateTask', { state: {task: data}) The purpose of this setup is to prevent dir ...

Exploring methods to modify the style attribute of a div tag in .NET

Using .NET, we need to access the CSS style of a div and input certain values in the code behind on page load. Since the div is located on the master page and this is another separate page, we are unable to add RUNAT="SERVER" to the div. ...

Compilation error in Angular 7 development process

Using Angular 7, npm 5.5.1 and node 8.9.0 In the terminal... npm run build:test <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5435252503736d736d73">[email protected]</a> build:test C:\Projects\fff ng ...

Increase the padding and add a border to separate the list items in bootstrap 4

I have a header with some links and I want to create space and add a border between them. I attempted using ::before pseudo-content, but it's not displaying the content where I intended. .header_links_ul { list-style: none; margin: 0; paddin ...

Tips for sending an Object within a multipart/form-data request in Angular without the need for converting it to a string

To successfully pass the object in a "multipart/form-data" request for downstream application (Java Spring) to receive it as a List of custom class objects, I am working on handling metadata objects that contain only key and value pairs. Within the Angula ...

Saving the initial state value in a variable in Vue.js is a crucial step in managing and

My dilemma involves an object in the Vuex store containing data that I need to utilize within a component. I have successfully accessed the data using a getter in the component. However, I am facing a challenge in preserving the initial value of this objec ...

Incorporating custom CSS and HTML into the link is essential for enhancing the appearance of KnpMenu

I'm working with the KnpMenuBundle and I need to customize a link that has the route 'uri'=>'#'. How can I achieve this? The desired link should be styled like this: <a href="#" class="js-sub-menu-toggle"> &l ...