Several buttons, each requiring to show distinct text

Currently, I am attempting to enhance an existing project that was graciously created for me. I must admit, I am quite new to this, so please be patient with me!

In my project, there are 9 buttons, each triggering the display of a different image upon being clicked. This functionality is already in place and working flawlessly. However, I now require each button to also showcase distinct text content, which I'm struggling with...

Here's a snippet of the code:

var Form = React.createClass({
getInitialState: function(){
  return {
    shirtState:'button',
    image:null,
    color:'white',
    colornotice: 'white shirt temp',
    shirtName:'',
    bandName:'',
    bandcampUrl:''
  }
},
handleColorChange: function(e){
  e.preventDefault();
  color = e.target.value
  this.setState({color: color, colornotice: color +' THIS TEXT SHOULD VARY FOR EACH BUTTON'})
},

The part where it says "THIS TEXT SHOULD VARY FOR EACH BUTTON" needs to dynamically change depending on the button clicked.

Below are the buttons:

<div className="buttons">
          <button className="color color-white" onClick={this.handleColorChange} value="white"></button>
          <button className="color color-black" onClick={this.handleColorChange} value="black"></button>
          <button className="color color-blue" onClick={this.handleColorChange} value="blue"></button>
          <button className="color color-green" onClick={this.handleColorChange} value="green"></button>
          <button className="color color-orange" onClick={this.handleColorChange} value="orange"></button>
          <button className="color color-pink" onClick={this.handleColorChange} value="pink"></button>
          <button className="color color-purple" onClick={this.handleColorChange} value="purple"></button>
          <button className="color color-red" onClick={this.handleColorChange} value="red"></button>
          <button className="color color-yellow" onClick={this.handleColorChange} value="yellow"></button>
        </div>

Each button should contain predefined text that replaces the current placeholder:

{this.state.colornotice}

The changes in images triggered by the button clicks mentioned earlier are controlled in the CSS, which is functioning correctly. Here's a segment of it:

.color-blue{
background: #fff image-url("Blue-Transparent_2300x2415.png");
background-repeat: no-repeat;
background-position: center 0px;
background-size: cover;

This pattern continues for all 9 buttons.

I trust this explanation is clear. Thank you for any assistance you can provide!

Answer №1

Utilize the power of props:
(an example demonstrating ES6 and ES7 syntax for better understanding)

CustomButton.js

import React, { PropTypes } from 'react';

export default class CustomButton {
  static propTypes = {
    buttonText: PropTypes.string
  }

  render() {
    return (
      <button value={this.props.buttonText}></button>
    );
  }
}

MainApp.js

import React, { PropTypes } from 'react';
import CustomButton from './CustomButton';

export default class MainApp extends Component {
  constructor() {
    super();

    this.state = {
      text: ['green', 'yellow', 'purple']
    }
  }

  render() {
    let buttons = this.state.text.map(color => <CustomButton buttonText={color} />);

    return (
      <div>
        {buttons}
      </div>
    );
  }
}

Answer №2

Looks like I've got the solution!

switch(color) {
    case 'black':
      // perform specific actions
      this.setState({color: color, colornotice: color +' shirt is cool'})
      break;
    case 'blue':
      // execute certain tasks
      this.setState({color: color, colornotice: color +' shirt is trendy'})
      break;
    default:
      this.setState({color: color, colornotice: color +' shirt is stylish'})
  }

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

"When working with Vue projects, an error may occur stating "Parsing error: No babel config file detected" if the IDE is not opened at

Encountered an issue in VS Code with a Vue project, where if the project is not opened at the root directory, babel.config.js fails to load causing confusion for the IDE. All my files display an error on the initial character of any javascript/vue file st ...

Currently, my goal is to place a div underneath two other divs. Here is the code snippet that I am working

I am attempting to position the div with id 4 so that it appears after the divs with ids 2 and 3, which are placed next to each other. However, when I try to do this, I notice that the div with id 4 seems to start from the top itself. Even though the con ...

Having issues with NextJS create-next-app functionality

Having installed NextJS using both methods npm install next react react-dom and npx create-next-app appname several times, I expected the directories to be as follows: pages, api(_app.js, index.js), public, styles, .next, node_modules However, in MY proj ...

Troubleshooting an Ajax request in Google Scripts with a '$' variable bug

I am trying to implement an AJAX Request using the ajax() method. I have created the functions below on scripts.google.com, but encountered the following error: function AjaxCall() { var arr = { City: 'Moscow', Age: 25 }; $.ajax({ u ...

Whenever I try to include something within the `componentWillUnmount` function,

I'm currently learning React on my own. I've been trying to save session data in my componentWillUnmount method. However, when I add code inside componentWillUnmount, nothing seems to happen. I tried debugging by adding console logs and debugger ...

Tips for updating the appearance of material-ui table pagination

I'm looking to enhance the way table pagination is presented in material-ui. The current default display by material-ui looks like this: https://i.stack.imgur.com/d4k4l.png My goal is to modify it to look more like this: https://i.stack.imgur.com/A ...

Avoiding incorrect AJAX requests made by the user

I created a webpage that grants users X points when they click a button. When the button is clicked, it triggers an AJAX request using JQuery to a PHP file that handles awarding the points using POST method. However, since this is client-side code, the pa ...

Identifying click events using jQuery specifically

After a jQuery event is triggered on a form by a click event only, I want to add some code. The event may also be called in other situations. To detect when the event is triggered, this code can be used: $( ".grouped_form" ).on("wc_variation_form", funct ...

Upgrading from synchronous $.ajax() to AngularJS $http or vanilla JavaScript (XHR) for asynchronous calls

Presented below is a function that I am currently working with: function getDataAvailablity() { var isDataAvailable; $.ajax({ url: 'http://someurl/data.json', async: false, dataType: json }).success(function() ...

How to Improve Performance for 15,000 Socket.io Users

I am facing an issue with my chat application that has large chatrooms, with 15,000 users connected to a single room. Only a few have the privilege to write messages, so in theory, there should not be a significant load on the server. However, I have obser ...

Update only specific fields in Mongoose using FindOneAndUpdate without affecting the values of the other fields

I am looking to enhance the ability to only update the fields that the user has selected for updating. Currently, if I leave some inputs blank, they end up as null in the database. This pertains to the backend router.put('/user/:id', async (req, ...

Component fails to re-render after token refresh on subsequent requests

Here is my axios-hoook.js file, utilizing the axios-hooks package. import useAxios from 'axios-hooks'; import axios from 'axios'; import LocalStorageService from './services/local-storage.service'; import refreshToken from &ap ...

I am able to see the Redux props showing up in Redux DevTools, but for some reason they are not

I am facing an issue where I am passing a Redux prop to a component that is fetched from a payload. The payload successfully updates the state in my reducer and the component receives the prop (an array of objects fetched in the action) according to my Red ...

Tips for showcasing an item with the chosen value in a dropdown menu

Below is the object I created: export default { data() { return { language: { "en": { welcomeMsg: "Welcome to New York City" }, "de": { ...

CSS styling not functioning properly

After spending a considerable amount of time on this issue... <div id="pager" style="top: 5px; position: relative; " class="pager" > <form> <img src="http://tablesorter.com/addons/pager/icons/first.png" alt="first" class="first" ...

Error: Attempting to use a React hook in a non-functional component in

I developed a simple application for educational purposes that features a contact book allowing users to add and remove new contacts. The functionality is consolidated on one page as shown in the code snippet below: index import styles from '../style ...

Attempting to personalize the CSS for a tab within a table in Material design is unsuccessful

Within my Angular 5 application, I have implemented the Material API. One of the components in my project is a table with 2 tabs structured like this: <mat-tab-group> <mat-tab> <mat-table> <!-- content --> </mat- ...

Ways to modify the gap between buttons using CSS

I am faced with a design challenge on my home page. I want to add some spacing between the buttons so they are not too close to each other, but for some reason margin-top and margin-bottom properties are not working as expected. Can you help me figure out ...

Sorting content using jQuery local storage

I've been grappling with how to effectively sort the localstorage data output for quite some time now. Specifically, I'm looking to sort the output in ascending order based on the stored product IDs. Does anyone have a solution to tackle this iss ...

Using the MoveToElement and click functions in Protractor with Node.js for automated browser

Trying to click on a checkbox in our application. I have successfully implemented it in Selenium Java using the code below, but struggling to do the same in Protractor Node.js. Any assistance would be appreciated. Selenium- Java : Actions actions ...