I am very new to React.JS, trying to wrap my head around it. So my intention is this.
Toggle between two different App(Counter and Random) based on button clicked.
I just want to toggle between two different DIV based on button clicked
Counter.JS
import { useState } from "react"
import './index.css';
function Counter(){
var [count,setmyname] = useState(0);
function Increment(){
setmyname(count = count+1);
console.log(count)
}
function Decrement(){
setmyname(count = count-1);
console.log(count)
}
function Reset(){
setmyname(count = 0);
console.log(count)
}
return(
<div className="center">
<div className="counter_app">
<h1>Counter App</h1>
<h1 className="count">{count}</h1>
<div className="button_class">
<button className="increment" onClick={Increment}>Increment</button>
<button className="decrement" onClick={Decrement}>Decrement</button>
<button className="reset" onClick={Reset}>Reset</button>
</div>
</div>
</div>
)
}
export default Counter`
Random.JS
function Random(){
var [number,SetRandom] = useState(0);
function GetRandom(){
SetRandom(Math.floor(Math.random() *10));
console.log(number);
}
return(
<div className="random_center">
<div className="random_app">
<h1>Random App</h1>
<button className="random" onClick={GetRandom}>Random</button>
<p>{number}</p>
</div>
</div>
)
}
export default Random
App.JS
import Counter from "./counter"
import { useState } from "react"
import Random from "./random"
import ReactDOM from "react-dom/client"
function App(){
var [button,SetButton] = useState(1);
function GetDiv(){
}
return(
<div className="container">
<button onClick={}>Counter App</button>
<button onClick={}>Random App</button>
</div>
)
}
export default App
Index.JS
const root=ReactDOM.createRoot(document.getElementById("root"));
root.render(<App></App>
);
I have added four JS files for toggling between the button. I am sure there might be a better way to do this. I am not sure how to do DOM Manipulation In React.JS. Let me know how to do it. Thanks so much.
2
Answers
In React, you don’t need to directly manipulate the DOM to toggle between components (like Counter and Random). Instead, you use state to conditionally render components. Here’s how you can update your files to achieve the desired toggle functionality:
counter.js:
random.js:
app.js:
index.js:
This approach uses React’s state management, eliminating the need for direct DOM manipulation and ensuring efficient UI updates. It is highly scalable, allowing additional components to be integrated easily, such as adding a third button and component. Moreover, the code remains simple, readable, and easy to maintain.
I believe your Index.Js is fine.
To switch between both, in your App.js you use React’s States (https://react.dev/reference/react/useState) as you’ve guessed, but you’re not using it correctly :
Using the React Conditional Rendering, you can make the one that you want show up