Search code examples
reactjsconditional-statementsconditional-rendering

How to add React components based on conditional statements evaluating a boolean based on a changable counter


Good morning,

I am attempting to add React components based on a counter value and then use conditional statements to determine whether or not they are rendered. In other words, I want to add components below a component when a "+" is clicked and then remove those elements when an "x" is clicked. The code I am attempting to use is as follows:

let differentials = 0;

const diffAdded = () => {
    if (differentials < 2) {
        differentials++;
    }
}

const diffRemoved = () => {
    if (differentials > 0) {
       differentials--;
    }
}
    return (
        <article className="addJob">
            <header className="margin title">
                <p>Add new job:</p>
            </header>
            <main>
                <form>
                    <section className="form-group">
                        <label className="margin" htmlFor="name">Job name</label>
                        <input type="text" id="name" className="form-control anInput"                 
                             placeholder="Enter job title" required />
                        <label className="margin" htmlFor="hourly">Hourly rate</label>
                        <input type="number" id="hourly" className="form-control anInput" 
                             placeholder="$##.##" required />
                    </section>
                    <section>
                        <label className="margin">Shift/night differential?</label>
                        <i className="fa fa-plus add-button margin" aria-hidden="true" onClick={() =>     
                                                                            diffAdded()}></i>
                    </section>

                    //this section is the one I want to changed based on counter value
                    <section>
                        {differentials > 0  && <DiffSection id="diff1" diffRemoved={() =>     
                                                                        diffRemoved()}/>}
                        {differentials > 1 && <DiffSection id="diff2" diffRemoved={() =>                             
                                                                        diffRemoved()}/>}
                    </section>
                    <section className="submit-button" onClick={() => jobAdded(
                        document.getElementById('name'),
                        document.getElementById('hourly'),
                        document.getElementById('diff1'),
                        document.getElementById('diff2')
                    )
                }>
                    <p>Submit</p>
                </section>
            </form>
        </main>
        <section className="footer" onClick={() => nameClicked()}>
            <span className="user-name">{props.userData.name}</span>
        </section>
    </article>
    );
}

I have attempted this same thing by instantiating an empty array and then pushing the component when the "+" icon is clicked.

Here is a simplified version of what I am trying to do in code sandbox:

https://codesandbox.io/s/muddy-mountain-rll71?fontsize=14&hidenavigation=1&theme=dark

What do I need to do to get this to work?

Thanks


Solution

  • Changing local variables does not trigger component's lifecycle, that can be done by using React API like useState.

    That's basic concepts of React, you should refer to State and Lifecycle, Component State.

    export default function App() {
      const [counter, setCounter] = useState(0);
    
      const plusClicked = () => {
        if (counter < 2) {
          setCounter(p => p + 1);
          console.log(counter);
        }
      };
    
      const minusClicked = () => {
        if (counter > 0) {
          setCounter(p => p - 1);
          console.log(counter);
        }
      };
    
    return (...)
    }
    

    Edit crazy-cookies-2jb2e