Create a new `div` component for a child element when the button is clicked in ReactJS

I am attempting to incorporate a child div component (div-col inside of div-row) when the button is clicked. In this case, I am changing the card layout from grid to list view using Bootstrap classes.

If the current view is set to grid view:

<div className="row">
  {notes.map((item, key) => {
    return <Noteitem />;
  })}
</div>

On clicking the button for listview:

<div className="row">
  <div className="col"> 
    {notes.map((item, key) => {
      return <Noteitem />;
    })}
  </div> 
</div> 

Do I need to handle separate DOM return statements for both cases? Open to suggestions for alternative approaches as well.

Answer №1

Define a state called myView with a default value of 'GridView'. When the listView button is clicked, update the state to 'ListView'.

To use this state, render the following:

{
  myView === "GridView" ? (
    <div className="row">
        {notes.map((item, key) => {
          return <Noteitem />;
        })}
    </div>
  ) : (
    <div className="row">
      <div className="col">
        {notes.map((item, key) => {
          return <Noteitem />;
        })}
      </div>
    </div>
  );
}


Answer №2

Following @Bee's answer, but with a more concise and detailed approach:

const [grid, setGrid] = useState(false)

return (
    <button onClick={() => setGrid(!grid)} />
    <div className="row">
       <div className={grid ? "col" : ""}> 
         {notes.map((item, key) => {
            return <Noteitem  />;
         })}
      </div> 
    </div>
)

Description

This code snippet keeps the div element in the document object model (DOM) and dynamically switches between the classes col and null. By toggling the grid view on and off using the onClick attribute of the button, the state value remains as a Boolean for easy reference. The ternary operator is utilized to assign the appropriate className value to the 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

The slider causing conflicts with widgets and content positioned below it in an HTML layout

When implementing a slider with a fade effect, there seems to be an issue with the placement of widgets on the homepage. The problem arises from the margin-top setting as when images change in the slider, the widgets clash with the slider. During the trans ...

How to align text to the bottom of a div using CSS

I am struggling to position the text 'About' at the bottom of an image. The red line marks the spot where I want the text aligned at the bottom. However, every method I try results in inconsistent outcomes when viewed on desktop and mobile device ...

FireFox is causing issues with both ng-view and Angular functions, rendering them unusable

My AngularJS sample application is running smoothly in Google Chrome, but when I tried to test it in Firefox, I encountered issues with ng-view and other functions not working properly. This is the structure of my application: Index.html <!DOCTYPE ht ...

What is the best way to locate an item reference for a specific DOM element?

Imagine a vast DOM structure with approximately 10,000 HTML elements, including 1,000 span tags. None of the span elements have any identifiers and are buried deep within other objects with long, complex Xpath paths that are not user-friendly for selectio ...

Utilizing SQL with PHP for Dynamically Populating an HTML Dropdown Menu

Having some trouble with PHP and SQL for a select option in an HTML form. I want to fill the select options with data from my sql table and then populate selections into a different table in sql. This is my first time working with PHP and SQL, so please be ...

Is there a way to detect browser errors using JavaScript or Angular 2?

On the back-end, I am looking to add these uncaught errors to the log file. These errors are not being captured in angular2. How can I go about reading and handling these errors?https://i.sstatic.net/Kljon.png ...

Transferring information among PHP web pages using a list generated on-the-fly

I am working with a PHP code that dynamically generates a list within a form using data from a database: echo '<form name="List" action="checkList.php" method="post">'; while($rows=mysqli_fetch_array($sql)) { echo "<input type='pas ...

Tips for properly including my Dialog Flow access token in the environment file within the Angular CLI

I am currently in the process of creating a bot using angular cli and integrating dialog flow's API. The issue I am facing is that when I perform debugging in Chrome, I encounter the following error logs: ApiAiClientConfigurationError columnNumber: ...

The Checkbox generated by Javascript is failing to properly close the tag

When I generate a checkbox in this manner and insert it into my table's [TD] tag: let checkbox = document.createElement('input'); checkbox.type = 'checkbox'; td.appendChild(checkbox); It yields: <tr> <td> ...

Unable to load routes from ./app.js in the file ./src/routes/index.js

Just dipping my toes into the world of nodejs. I recently moved all my routes from app.js to a separate file located at PROJECT_DIR/src/routes/index.js. However, when I try to open the page in my browser, it displays "Cannot GET /wines". Below are snippets ...

Personalized color scheme for calendar td

I am facing an issue with my event calendar where I want to change the background color of td. I came across a helpful solution in this question, but it did not fully solve my problem. When I implemented the following jquery: $('[class*="fc"]'). ...

Clicking an AngularJS button within a form is causing an unexpected page refresh

I am facing an issue with adding a new input field on click. I have two buttons, one to add and another to remove the input box. When I click on the add button, it should add a set of input boxes, but currently, it only adds one and refreshes the page, dis ...

The OrhographicCamera is having difficulties capturing the entire scene in its render

Recently, I have been working on rendering a scene using three.js and WebGL in an isomorphic manner. In my research, I came across suggestions to use the OrthographicCamera for this purpose. However, upon implementing it, I noticed some strange outcomes. A ...

How to center a div with a overlay in CSS?

I have created an overlay with a div on top of it, and I am currently struggling to center the div over the overlay. I have tried adjusting the left and right properties, but nothing seems to be working. .request-estimate { position: absolute; ...

How can you use C# code to control the visibility of a table row in HTML?

I am trying to display or hide a table row based on the current month using DateTime.Now.Month in my HTML code, but I can't seem to remember the correct syntax. The code I have tried is not working as expected. Can anyone help me with the correct synt ...

Utilizing Redux with React to fetch and handle JSON data from given API endpoint

The assignment I'm working on requires us to fetch JSON data from a specific endpoint called url and display it in an Excel-like table using React, Redux, and Redux-Thunk. I successfully managed to retrieve and display the data in a table by utilizin ...

Setting the minimum supported screen size in MUI/ReactJS: A comprehensive guide

Currently, I am utilizing Material UI 5.6 within a web application that necessitates a generous viewport size. My objective is to establish a minimum screen width for the entire app so that: In cases where users open the app on devices with narrower width ...

Please refresh the page in order to utilize the newly updated cookies

I have a specific process that involves: A button triggers the function fcn1 and redirects to a page called p1 Function fcn1 retrieves 6 strings from a backend SQL database The 6 strings are then stored in cookies Page p1 reads the 6 cookies and displays ...

Running a setTimeout function within the context of a jQuery each

My goal is to animate characters one by one, but for some reason the following code isn't functioning as expected: $('.overlay-listing').hover(function(){ var idx = 1; $('.strip-hov span', this).each(function(){ if ...

What is the best way to display loading details during a data loading process within a useEffect hook?

Whenever a specific custom React component I've created is initially mounted, it utilizes useEffect to initiate a lengthy multistep process of loading data that will later be rendered. Since the component isn't always rendered, this costly proces ...