[React] Checking a checkbox to change the color of a specific input into an array[closed]

Hi everyone,

In my form component, I have to make a functionality which if user checks the checkbox under the input of his choice, the chosen input will become like this : 49

But, first as I would like to understand how it’s working, I would like to make the chosen input red. Below is a little scheme of what I would like to do:
01

But the inputs are an array of objects and the checkboxes are originally not included into the array and I only need one checkbox under each input. I can have one checkbox under each input but I can only make all the input red and all the checkbox checked and not one specific input nor checkbox. But since I did some maps in my states to compact it and add a list with multiple checkboxes, it’s not working at all. I think it’s because I add a specific function to handle the checkboxes list and it’s overridden my function which handle others checkboxes. In addition, if one input is added, I need to add one checkbox which, if checked, will make the added input red.

Here is my code :

FormTeacher.jsx

const initState = {
emptyQuestion: false,
  modes:{
    evaluation: true,
    niveau: true,
    certification: true,
    exercice: true
  },
appConsigne: "",
questionElements: Array(3).fill(null).map((nullElem, i) => ({
    id: i,
    questionElement:""
    })
  ),
}
class FormTeacher extends React.Component {
  constructor(props) {
    super(props);
      this.state = initState
  }
handleQuestions = idx => evt => {
    evt.persist();
    const newQuestionElements = [...this.state.questionElements];
    newQuestionElements[idx].questionElement = evt.target.value;

    if (newQuestionElements.every(el => el.questionElement.length)) {
      newQuestionElements.push({
        id: newQuestionElements.length,
        questionElement: "",
      });
    }
    this.setState({
      questionElements: newQuestionElements
    });
  };
submitHandler = (event) => {
    event.preventDefault();
    /*event.target.className += " was-validated";*/
  };

  changeHandler = (event) => {
    event.persist()
    this.setState({ [event.target.name]: event.target.value });
  };
handleCheckbox = (event) => {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }
  renderModeCheckboxes = () => {
    const modes = ['evaluation', 'niveau', 'certification', 'exercice'];

    return modes.map((modeCheckbox, i) => {
      return (
        <label key={i}>
          <MDBInput label={modeCheckbox} type="checkbox" id={"checkBox"+i} name={modeCheckbox} checked={this.state.modes[modeCheckbox]} onChange={this.handleModeCheckboxes} />
        </label>
      )
    })
  }

  handleModeCheckboxes = (ev) => {
    const val = ev.target.checked;
    const name = ev.target.name;
    let updatedMode = Object.assign({}, this.state.modes, {[name]: val})

    this.setState({
      modes: updatedMode,
    })
  }

  render() {
    const{evalStatus, selectTest, updateFormTeacher} = this.props;
    const{appConsigne, questionElements, reponses, reponseCorrecte, appLangueConsigne, modes, appLangue, emptyQuestion} = this.state;

    const displayQuestions = questionElements.map((questionItem, idx) => (
      <div key={questionItem.id}>
      <MDBInput
        value={questionItem.questionElement}
        name="questionElements"
        type="text"
        id={'displayQuestions'+questionItem.id.toString()}
        label="question"
        required
        onChange={this.handleQuestions(idx)}
        style={{ maxWidth: "5rem" }}>
        <div className="valid-feedback">Looks good!</div>
      </MDBInput>
      <MDBInput label="vide" type="checkbox" id={"checkBox"+idx} name="emptyQuestion" checked={this.state.emptyQuestion} onChange={this.handleCheckbox} />
</div>
    )
  );
return (
      
            <MDBCard>
              <MDBCardBody>
                <div>
                  <form
                    className="needs-validation"
                    onSubmit={this.submitHandler}
                    noValidate
                  >
<MDBCol md="4">
                    
                        {this.renderModeCheckboxes()}
                      </MDBCol>
                      <MDBCol md="4" style={{ maxWidth: "20rem" }}>
                      
                        <MDBInput
                          value={this.state.appConsigne}
                          name="appConsigne"
                          onChange={this.changeHandler}
                          type="text"
                          id="materialFormRegisterNameEx"
                          label="consigne"
                          required
                        >
                          <div className="valid-feedback">Looks good!</div>
                        </MDBInput>
                      </MDBCol>
                    </MDBRow>
                    <MDBRow>
                      {this.state.emptyQuestion === true ? (<MDBCol md="4" style={{ maxWidth: "8rem", backgroundColor: "red" }}>
                        Q: {displayQuestions}
                      </MDBCol>) : (<MDBCol md="4" style={{ maxWidth: "8rem" }}>
                        Q: {displayQuestions}
                      </MDBCol>)}
                    </MDBRow>
<MDBBtn color="success" type="submit" onClick={() => { updateFormTeacher({appMode, appEtape, appConsigne, questionElements, reponses, reponseCorrecte, appLangueConsigne, appLangue, modes, emptyQuestion}); this.showDisplayQuizz()}}>
                      Preview
                    </MDBBtn>
                  </form>
                </div>

            </MDBCard>
          
    );
  }
}

export default FormTeacher;

I would be very glad and grateful if somebody could give me a hint on where I could start to resolve my problem.:blush:

So we can test the full code, can you provide your project via Codepen, jsFiddle, or sandbox link?

Thank you for your reply. :blush: I am writing it into a sandbox at the moment. But as the API I am using is private and the application as several components, I need to make some adjustments so I need some time. I will update this thread when it will be ready.

You could just provide a sample return value from the API and set it to a variable to be used, so we can see the structure of what is returned.

Thank you for your piece of advice.:blush: As it’s already evening in the country I am living in and as I am very tired, I will continue to work on it tomorrow.

@RandellDawson I followed your advice and put an example of what I am receiving from the API into a variable but it’s not working and I don’t understand why. So here is my codesandbox : https://codesandbox.io/s/p31y0o75o7

I don’t know if something can be make out of this, so just in case, I will try to make it works by doing a little back-end (and hoping it will works)

This would be so easy to solve with vanilla JS.

@RandellDawson

Hi everyone,

Sorry I took so long to update this thread. In fact I was using some non free MDB React component so I had to use another framework to be able to show you all, the problem I wrote about on top of this thread. I still have this problem but I can now show you all my code in sandbox. :blush: So here is the link : https://codesandbox.io/s/p31y0o75o7 (sorry for the ugly form)

I hope now some people will be able to help me. :blush:

Hi everyone,

Sorry for bothering you again. I would like to inform all of you that I could solved the problem between my two functions but it’s still hard for me to make only one input red. Moreover I have now a controlled to uncontrolled component error in the console.:sweat:

Where could I start to resolve this problem ?:thinking: I admit I feel really lost with this.

Thanks to have read my message. :slight_smile:

Hi everyone,

I successed in solving this problem (except it doesn’t work when input are added for now) so this thread is closed now. :wink: