2

I am new to React JS. I am creating a simple web page using React-bootstrap. I need to change the Heading color and the text color, and also the background color, when I click a button. For an example, when I click the Green button, it will make changes in heading color to dark Green and text part to light green within the green color background. What should I add the code for manage this ?

Here my code

    import React, { Component } from 'react';



    class Page extends Component {

    render() {

        return (
            <div>

                <div style={{ background: "#f0f0f0f" }}>
                    <h3 style={{ color: 'Black' }}>Heading</h3>
                    <p style={{ color: '#706c61' }}> This is a text... </p>
                </div>
                
                    <div>
                        <button> White </button>
                        <button> Purple </button>
                        <button> Red </button>
                        <button> Green </button>
                    </div>
               
            </div>
        );
    }
}

export default Page;
DecPK
  • 24,537
  • 6
  • 26
  • 42
Aye
  • 55
  • 1
  • 9
  • What did you try to solve that on your own? The way to do this is covered by the tutorial. – trixn Mar 25 '21 at 09:26

2 Answers2

2

store the colors in the state as below:

this.state = { heading: "Black" };

and then assign them to the elements:

  <h3 style={{ color: this.state.heading }}>Heading</h3>

then you can change it by onClick event of buttons:

<button onClick={() => this.setState({ heading: "green" })}>
            {" "}
            Green{" "}

sandbox

alisasani
  • 2,808
  • 1
  • 7
  • 15
2

You can use States to control color dynamically.

import React, { Component } from 'react';



class Page extends Component {
 constructor(props){
   super(props);
   this.state={color:"black"}
}
    render() {

        return (
            <div>

                <div style={{ background: "#f0f0f0f" }}>
                    <h3 style={{ color: this.state.color }}>Heading</h3>
                    <p style={{ color: '#706c61' }}> This is a text...</p>
                </div>
                
                    <div>
                        <button onClick={()=>this.setState({color:"white"})}> White </button>
                        <button  onClick={()=>this.setState({color:"purple"})}> Purple </button>
                        <button  onClick={()=>this.setState({color:"red"})}> Red </button>
                        <button  onClick={()=>this.setState({color:"green"})}> Green </button>
                    </div>
            </div>
        );
    }
}

export default Page;

Sandbox - Link

TechySharnav
  • 4,869
  • 2
  • 11
  • 29