Really struggling with react

So, I’m really struggling with React… It’s just a lot different than regular JavaScript.

I’m just messing around and trying to get comfortable with what I’ve learned before moving on and the structure of things in React just really throw me off.

My question is how come I don’t have access to the variable total outside of my sumOfTwo function? Shouldn’t I have access to it within the product function?? I can’t add anything to total because I don’t actually have access to it outside of the sumOfTwo function. I’d rather have {total} in my p tag and not calling the actual function.

export default function Product() {
    function sumOfTwo(num1, num2) {
        const total = num1 + num2
        return total
    }
    
const number = 98
const numberTwo = 50

    return (
        <div>
            <button>click me!</button>
            <button>Click to add 1!</button>
            <p>{sumOfTwo(number, numberTwo)}</p>
        </div>
    )
}

I did fix this problem (if this is a proper way of doing it) but I still don’t understand why I wouldn’t have access to total outside of that function because it’s all within one function.

let total

export default function Product() {
    function sumOfTwo(num1, num2) {
        total = num1 + num2
        return total
    }

const number = 98
const numberTwo = 50

sumOfTwo(1, 5)
    return (
        <div>
            <button>click me!</button>
            <button>Click to add 1!</button>
            <p>{total}</p>
        </div>
    )
}

As said, that is just plain JS and scopes. If you declare a variable inside a function only that function scope and any inner scope will have access to it. You have to return it out of the function if you want access to it outside the function.

function Product() {
  function sumOfTwo(num1, num2) {
    const total = num1 + num2;
    return total;
  }
  console.log(sumOfTwo(2, 3)); // 5
  console.log(total); // ReferenceError: total is not defined
}

Product();

If you use state variables anything inside the component has access to them and the component will re-render when they change.

Example
import { useState } from 'react';

export default function App() {
  const [first, setFirst] = useState(0);
  const [second, setSecond] = useState(0);
  const [total, setTotal] = useState(0);

  function handleTotal() {
    setTotal(first + second);
    setFirst(0);
    setSecond(0);
  }

  return (
    <div className="App">
      <input
        type="number"
        value={first}
        onChange={({ target }) => setFirst(+target.value)}
      />
      <input
        type="number"
        value={second}
        onChange={({ target }) => setSecond(+target.value)}
      />
      <button onClick={handleTotal}>Get Total</button>
      <p>{total}</p>
    </div>
  );
}
1 Like

This is absolutely not how JavaScript, or basically any other commonly used programming language, works. This isn’t a “React” thing. You have access to variables that are already defined

function example () {
  let aVariable = "I'm a string"

  function nestedFunction () {
    // I can access "aVariable" here
  }
}

But you can’t access variables declared in a deeper scope from outside that scope

function example () {
  function nestedFunction () {
     let aVariable = "I'm a string"
  }

  // I absolutely cannot access "aVariable" here
}
1 Like

is this what you were suggesting? I realize my mistake, but I want to make sure this is a proper way of doing this. So now all of the nested functions would have access to total correct? This would also be a real world (generic) example of closures, wouldn’t it?

export default function Function() {
    let total
    function sumOfTwo(num1, num2) {
        total = num1 + num2
        return total
    }
    sumOfTwo(1, 4)
    return (
        <div>
            <button>click me!</button>
            <button>Click to add 1!</button>
            <p>{total}</p>
        </div>
    )
}

“Just initialize total with the result of calling sumOfTwo(1, 4)

this is the part I’m confused on because I can’t access total if it’s created in sumOfTwo()
Also, I was just messing around in react to try and get used to things and made a generic function, I didn’t intend to have to post anything to the forums, but I ran into a problem and decided to post.

closures were something I struggled with, so that is why I wanted to actually figure this out.

export default function Function() {
    function sumOfTwo(num1, num2) {
        return total = num1 + num2
    }
    sumOfTwo(1, 4)
    return (
        <div>
            <button>click me!</button>
            <button>Click to add 1!</button>
            <p>{total}</p>
        </div>
    )
}

I wasn’t aware you could initialize variables where you would pass arguments to a function. What would this be called? I’d like to do some research on that. I’ve never came across that.

Could you possibly give a slight example of what you mean by initializing a variable with a call to a function? I feel like I’m overthinking this.

Do you actually mean initializing a variable in here? sumOfTwo( > initialize in here <) I understand num1 and num2 are initialized when I call the function but how would I do that with total? considering it’s num1 + num2

so, like this?

export default function Function() {
    function sumOfTwo(num1, num2) {
         return num1 + num2
    }
    let total = sumOfTwo(1, 6)
    return (
        <div>
            <button>click me!</button>
            <button>Click to add 1!</button>
            <p>{total}</p>
        </div>
    )
}
Function()
1 Like

I can’t recall every doing this with a project, so this is new to me I believe. Thank you for your patience! as always, you’ve been a huge help.

Thank you to everyone else as well.

That’s how this stuff is. There is soooooo much stuff that it’s hard to keep track of it all. But with practice, it gets easier.

I’m off to work but I’ll check it out when I get back!

You’ll be surprised how much of struggling with React actually comes from not understanding JS syntax. React does lean heavily on modern JS syntax and notions and your ability to understand and learn react is directly related to your knowledge and udnerstanding of JS.

Yeah, there’s a lot of truth to that. I think people start working on React right when they are at the “I kind of, sort of understand about half of JS” and then React just assumes that you understand most of it very well. It’s very common to get the “this React makes no sense” post that just turns out to be a misunderstanding about JS.

I don’t know, I guess I went through the same thing.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.