Create a new feature in React JS that allows users to add a component to

I'm having trouble figuring out how to create a function that loads data (from a local json) into a li element, and then adds a new component to the clicked li upon click.

Here's an example of what I'm trying to achieve:

<ul>
    <li> 1 </li>
    <li> 2 </li>
    <li> 
        3 
        <div id="data">
        <!-- appended data -->
        </div>
    </li>
</ul>

When clicking on another li, I want the previously added element to be removed and the new one to be added. Essentially creating a row toggle effect.

If anyone could point me in the right direction with React for this scenario, it would be much appreciated.

import React, { Component } from 'react';
import Flowers from 'flowers.json';

class Flowers extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      isToggleOn: true
    };

    this.onClick = this.handleClick.bind(this);
  }


  handleClick = (e) => {
    console.log(this);
    console.log(e);
    console.log('li item clicked! ' + e.currentTarget);
    // appends to clicked div
    e.currentTarget.style.backgroundColor = '#ccc';
  }

  render() {
    const List = Flowers.map((flower) =>
      <li onClick={this.handleClick.bind(this)} key={flower.id} id={flower.id}>
        {flower.name}
      </li>
    );

    return(
        <ul>{List}</ul>
    );
  }
}

class App extends Component {
  render() {
    return (
      <Flowers />
    );
  }
}

export default App;

Answer №1

To keep track of the active flower, you can include its ID in your state. For example:

this.state = { ActiveFlowerID: null }

By setting ActiveFlowerID to null initially, no flower is considered active. Update the state in the handleClick method and render additional data for the flowers based on the matched flower ID and state.

I trust this explanation is beneficial to you.

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

Personalized AngularJS required text

After utilizing the built-in AngularJS directive required and encountering a validation error, I receive a small popup near the field displaying "Please fill out this field". My issue lies in needing the text to be displayed in another language. How should ...

Do not proceed with the form submission if the fields are left blank

I am facing a challenge with organizing two sets of data, "heat" and "cold", obtained from an external provider. The data is messy and I have trimmed down the code to focus on the main issue at hand. Both "heat" and "cold" have properties that users need t ...

What is the cause behind the failure of this regular expression in JavaScript?

I have been struggling to make this code display "matched!" for the specific string. I've tried various methods but nothing seems to be working. Here's the HTML part: <div id="ssn">123-45-6789</div> And here's the JavaScript p ...

Exploring the Redux Store within a Utility File

TLDR: How can I access the latest Redux State in an external "Util" file for my startPlaylist function? Imagine having a playlist feature within an app where you can start the playlist from various sections. To avoid duplicating code, I created a "startPl ...

transferring a delicious cookie to the browser

I have successfully integrated a basic login system using angular, express, and passport.js into an existing project by following the file structure and coding standards provided in angular-passport. Currently, users can sign up and log in without any iss ...

Tsyringe - Utilizing Dependency Injection with Multiple Constructors

Hey there, how's everyone doing today? I'm venturing into something new and different, stepping slightly away from the usual concept but aiming to accomplish my goal in a more refined manner. Currently, I am utilizing a repository pattern and l ...

Refreshing the page causes the HTML input to be cleared

My dilemma involves a javascript function that stores the value entered in an <input> field to a cookie, followed by a page refresh. The purpose of the refresh is to allow the server side to re-render the page using the cookie values. My concern is ...

The typical actions of the table elements

When I view my table on large screens, the TH elements are displayed at the top. However, when I switch to a mobile device, these THs move to the left side instead. Is this the default behavior of TH elements in tables? I am utilizing the 'responsive- ...

Steps for populating roles in Firestore using the react-redux-firebase package

I am currently using a package and I am looking to implement this method to transfer data from the 'roles' collection in my firestore to my firebase/profile data in the redux state. According to the documentation, the roles collection should be ...

Is it possible that scrollIntoView() function is not available when the page is first loaded?

Within my FAQ page, I have concealed the answers to each question by default, displaying only the questions with a link that allows others to reference each specific question through an embedded id anchor. Here is the structure of the question format: &l ...

The glTF file lacks visible content

My goal is to showcase a glTF file using Three.js. To bypass CORS policy, I have opted for a local server called Servez. While everything runs smoothly on Mozilla Firefox without errors, the content does not appear. However, when attempting the same on Chr ...

Struggling to traverse through intricate layers of nested objects in React and showcasing them without going crazy

Dealing with an API that returns data structured in deeply nested objects has been a challenging task. The goal is to extract specific data from these nested objects and then display them within a React project. Despite numerous attempts, finding a simple ...

Padding needed for floated <li> items in horizontal menu

I'm attempting to design a horizontal top header featuring a main navigation stacked above a sub-navigation. Both navigations are constructed using <ul> elements with floated <li> items. The sub-navigation mysteriously has excess horizonta ...

Shadows and reflections are not supported on Threejs PlaneGeometry

I'm relatively new to the world of 3D graphics and three.js, and I'm struggling to figure out how to achieve individually illuminated polygons on a PlaneGeometry. I've been working on applying some noise to the vertices' z-values in ord ...

Variability of pixel dimensions on various devices

When it comes to front-end design in CSS, the use of pixels as a measurement is quite common. However, with varying display sizes and resolutions, one might wonder how relevant this fixed pixel size really is. Is there a way to utilize real-world measure ...

Trying to retrieve JSON data from an API in VueJS and successfully logging the results, but struggling to render the data on the page. (I

Having recently transitioned from React to VueJs, I encountered a problem where fetching data using axios.get returns a successful response in the console.log. However, when trying to iterate through the array with v-for, nothing is rendered. If you have a ...

Selenium: Mastering the Art of Label Clicking

I'm attempting to interact with this element using Python's Selenium library by employing the following code snippet: driver.find_element_by_('publicForm_customFields').click() Unfortunately, I encountered the following error message: ...

Caution: Material-UI in conjunction with Next.js and express is generating a warning message regarding the mismatch of the `className` prop between the server and client

Whenever I directly reload the /login and /account pages, issues arise. These two pages contain Material-UI components. https://i.sstatic.net/h7qww.png Additionally, here is a glimpse of my express server: Server.js ...

Show the entered user data in a separate Div when the button is clicked

Whenever a button is clicked, I am currently able to show the user input from the textbox. However, it always displays in the same Div. The HTML file with the textbox and button- <input type="text" name="inputText"><br> <tr> &l ...

Ways to create spacing between vertically stacked columns in Bootstrap

I have created a website using Bootstrap and PHP to display data from 18 categories in columns. The code for listing the categories in a single row is shown below: <div class="row"> <?php foreach($categories as $val){?> <div class="col ...