Search code examples
javascripthtmlreactjsnavbarreact-bootstrap

How To Display Variable in React Navbar?


How would I get to display the variable temp inside a <Navbar.Text>? Using $ or "$" does not work and just shows the string

Do I need to have weather find function inside the navbar, do I need to do more linking? I'm a beginner to web development so I'm sorry if its something obvious.

imports...
...

weather.find({degreeType: 'F',search: ''}, function(err, result) {
  if(err) console.log(err);
  //console.log(result[0].current.feelslike)

  const temp = result[0].current.feelslike
});

export default function NavBar (){
  const [show, setShow] = useState(false)
  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);
    return(
      
      <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark">
         <Navbar.Brand as={NavLink} to= '/' className={"px-3"}>
           <h4 className={"fontSize4"}>Home</h4>
         </Navbar.Brand>
         <Navbar.Toggle aria-controls="responsive-navbar-nav" />
         <Navbar.Collapse id="responsive-navbar-nav">
            <Nav className="mr-auto">
              <NavDropdown title= "Tools" className={"px-3 h3"} id="collasible-nav-dropdown">
...
...
...

              <Navbar.Text>
                "$temp"
              </Navbar.Text>
         </Navbar>
    );
  
}

Thanks


Solution

  • The temp variable needs to be wrapped in brackets and declared in the same scope as it is used. Right now, the only thing that has access to the temp variable is any code you put after const temp = result[0].current.feelslike.

    What you need to do is move the weather.find() into the NavBar class (like you mentioned in the comment), and create a new hook for the temp variable, so it can be updated. Using a hook instead of declaring a variable allows React to change the variable whenever it is rendered.

    export default function NavBar (){
      ... other code
      const [temp, setTemp] = useState(0);
    
      weather.find({degreeType: 'F',search: ''}, function(err, result) {
        if(err) console.log(err);
        setTemp(result[0].current.feelslike)
      });
        return(
          ... other code
          {temp}
          ... other code
        );
    }
    

    Another thing to note:

    Whenever you set a className attribute, you don't need to put brackets around the class name. Just the quotes are needed.

    className="nameOfCSSClass"
    

    If you want the home button to be of font size 4 (which is really small) then you can also do something like this:

    <p style={{fontSize: 4}}>Home</p>
    

    or just take out the className attribute all together because an h4 tag would make the font the size you need.