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

The active class in the Nextjs navbar only gets activated after being clicked a second time

I'm working on creating a custom header component for my next.js and tailwindcss application. I've noticed that the nav active class only appears when clicked on for the second time, but I want it to be active upon the first click. Can anyone poi ...

Creating NextJS Route with Dynamic Links for Main Page and Subpages

In my NextJS project, I have dynamic pages and dynamic subpages organized in the following folders/files structure: pages ├── [Formation] ├── index.js │ ├── [SubPage].js Within index.js (Formation Page), I create links like this: < ...

After encountering a character with CSS, begin a new line

I have a CSV spreadsheet with data that looks like this: <p>Features:• first feature• second feature• third feature• fourth feature• and so on (the total number of features is variable)</p> I want each feature to display on a new li ...

Executing various count() queries on a MongoDB using mongoose

Hey there, I consider myself a MongoNoob and I know this question has probably been asked before in various ways, but I haven't found a specific solution yet. Let's imagine I have two Moongoose Models set up like this: var pollSchema = mongoose. ...

What could have caused my javascript file to disappear from npm?

After creating a small library consisting of a .js file with commonly used functions, I placed it in the node_modules directory alongside my other packages. Everything seemed to be going well. A few days later, I decided to add a new package using npm ins ...

Is there a way to retrieve the sub-child menu data from a JSON file?

I am currently working on creating a horizontal menu from a json file. However, I am facing issues in retrieving the subchild elements properly. Below is an example of my json file: var data = [{ "menu":[ { "MenuId":1, ...

Trigger a complete page re-render with just one change in a child component

When working with two text boxes, one using hooks and the other the old style, I noticed that in Hook mode, whenever a user input changes the textbox value, the entire page gets rendered. However, with the old style, only the text box is re-rendered withou ...

Two sections that are supposed to have the same height, but one seems to be slightly taller than the other

Upon closer inspection: At first glance, they may appear identical at certain zoom levels. However, a more detailed examination through zooming in and out reveals a noticeable discrepancy. Firefox's default zoom may make them seem incorrect, while Chr ...

jquery ui dialog refuses to open

I am looking to initiate a dialog box, please refer to the comment below: var user_ids = $('.user_ids:checked').map(function() { return this.value; }).get(); var opt = { autoOpen: false, modal: true, width: ...

How can we redirect using an OnClick event handler in React.js?

I've been doing a lot of reading and trying to understand how to redirect using withRouter in React. However, I came across some information stating that when onClick occurs, the page should be redirected to a specific link. Additionally, I learned th ...

Redux repeatedly triggers re-rendering despite the absence of any changes in the state

This is my first venture into React-Redux projects. I was under the impression that React only re-renders when a component's state changes. However, I am currently facing confusion. The component is being re-rendered every 1 to 3 seconds even thoug ...

New posts causing Ajax functionality to cease functioning

<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#message').focus(); $('#message').keypr ...

Material UI TableCell lacks the ability to wrap a string and display it on a new line, unlike list items

I am currently working with a "Books" database in Material UI. The table consists of three columns: "Book Number", "Title", and "Chapters". My goal is to have each chapter displayed as individual list items, like so: Chapter 1 Chapter 2 Chapter 3 Inste ...

Emotion, material-ui, and typescript may lead to excessively deep type instantiation that could potentially be infinite

I encountered an issue when styling a component imported from the Material-UI library using the styled API (@emotion/styled). Error:(19, 5) TS2589: Type instantiation is excessively deep and possibly infinite. Despite attempting to downgrade to typescript ...

Retrieve the initial data of the AngularJS model upon button click

Previously, I was able to retrieve the initial values of the model using this.model.changed or this.model._previousAttributes in BackboneJS. Now, I am looking to achieve the same functionality in AngularJS, where I can track all changes made to the model ...

Encountering the error message 'React child elements cannot be objects' within the Autocomplete component when attempting to select a specific input

Encountering an issue with setting the value for a selected input in an Autocomplete Form in Material UI. The error message 'Objects are not valid as a React child' is displayed. Refer to the code snippet below: const [val, setVal] = useState({}) ...

The animation of a disappearing div with CSS is not stopping when hovering over it

Hello, I've been working on a snackbar feature that appears and disappears on a set timer but also needs to pause when hovered over. Unfortunately, the current setup with setTimeout and useState is causing issues with this functionality. I have looke ...

React Material UI issue: You cannot render objects as a React child. If you intended to display a group of children, make sure to use an array instead

I am encountering an issue with the code provided below and despite trying various fixes, I am unable to resolve it. componentDidMount() { axios.get('http://localhost:8080/home') .then((response) => { this.setState({ ...

Identifying when the mouse cursor changes on a website

Is there a way to detect when the mouse cursor changes as it hovers over different page elements? An event similar to this would be ideal: window.onmousecursorchange = function(e) { // e would provide information about the cursor // for example, ...

Discover the potential of JavaScript's match object and unleash its power through

In the given data source, there is a key called 'isEdit' which has a boolean value. The column value in the data source matches the keys in the tempValues. After comparison, we check if the value of 'isEdit' from the data source is true ...