NextJS: Replace

Viewed 24

I have a div in a Next JS application that displays the currency and price of a product once a user enters a product page.

<div className="flex">

<Image src={EuroCurrency} alt="Euro Sign} />
<h1 className="ml-5>9.800,00</h1>

</div>

Through an onClick event on a button, I want to exchange this div with another, evenly formatted but contextually different, div.

<div>

<Image src={DollarCurrency} alt="Dollar Sign} />

<h1 className="ml-5>9,500.00</h1>

</div>

This div would need to be hidden until the user clicks the aforementioned button.

I'm aware that this would be achieved through a state - but I'm uncertain on how to hide (and exchange) a complete div.

2 Answers

this is how you can use conditional rendering and useState together to switch the component

import React from 'react'
export default function App() {
  const [toggle, setToggle] = React.useState(false);
  
  return (
    <div className="App">
      {toggle ? ( <div >
      <h1 >9.800,00</h1>
      </div>): (<div><h1>9,500.00</h1></div>)
      }
      <button onClick={()=>{setToggle(!toggle)}}>Toogle</button>
    </div>
  );
}

Here you need to change the conditional rendering that suits you like

{toggle ? ( COMPONENT 1 ): ( COMPONENT 2 )}

I'm making a few guesses at what you're asking, but hopefully this example helps.

This is an example of a functional component that uses state to switch between rendering euro and dollars components:


import { useState } from 'react';

function MyAwesomeComponent(){ 

// expected state values are "dollar" or "euro"
// if you use TypeScript, you can enforce that,
// but I'm just a TypeScript shill :P

// "dollar" is the initial state
const [currency, setCurrency] = useState("dollar");

return(
  <div className="flex">

     { currency === "dollar" 
       ? <Image src={DollarCurrency} alt="Dollar Sign" />
       : <Image src={EuroCurrency} alt="Euro Sign" />
     }
    
     <h1 className="ml-5">9.800,00</h1>

     <button onClick={
         () => currency === "dollar" ? setCurrency("euro") : setCurrency("dollar")
       }
     > 
       Click to Switch Currency
     </button>

  </div>
)
}

There are plenty of other ways to do it. But notice how, instead of having the whole div rendered conditionally and duplicating code, I just render the specific Image component conditionally. Depending on your use case, you could conditionally render divs instead, any component can go in the two slots of the terney expression.

Related