Help with React!

I have an assignment and I am hung up on last part of it. It reads as follows:

Create an additional three blocks containing the same height and width

  • When I click on these blocks, it should cycle between red fill with a blue border, blue fill with a green border, and green filled with a red border.

The code I have is not working but actually came back error free is:

import React from 'react';
//import Rectangle from './components/Rectangle';
import style from './components/Block';
import './style/App.css';
//import Block from './components/Block'

function App(props) {

      const[color,setColor]=React.useState("red");
      const toggle = ()=> {
            setColor(color+10);
            if(color>=80){
                  setColor("#E0ffff")
            }
      };


  return (
    <div className="App">

        <div style={style.rectangle}></div>
        <div style={style.rectangle}></div>
        <div style={style.rectangle}></div>


        <div style={style.block1}></div>
        <div style={style.block2}></div>
        <div style={style.block3}></div>


        <button block onClick={toggle}>setColor("red")} style={style.block}>
              {toggle}

        </button>

        <button style={style.block}></button>
        <button style={style.block}></button>


</div>

  );
}

export default App;

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Excellent! Thank you!

I’m trying to understand how your code tries to do what you want. This is hard to test without access to your code. I assume that the second set of divs are what we’re talking about.

When I click on these blocks…

Then shouldn’t the onClick be on the divs?

… it should cycle between red fill with a blue border, blue fill with a green border, and green filled with a red border.

I can imagine different ways to handle this.

  1. Have a different style defined for each of those and use the state to switch between those.
  2. Have an array of the values and to use the state to index through those.
  3. Store an object on state with the relevant data and use logic in our toggle function to go through those.
  4. Use a custom, local reducer.

I think the first and second are the easiest. The last one is sexiest imho, but let’s go with the first.

So, you can have three styles, “block1”, “block2”, “block3”. Then your useState initializes with 1. Then in toggle, you increment the color number and then reset to 1 if you’re on 3. (It might be good to relabel your state variable.) And lastly, in your blocks, you can have style={style[`block${color}`]}.

1 Like