2 April 2020

If else Example in react js

  • Create Components folder under src folder
  • Add IfElseEXP1.js file and add below Code
import React, { useState } from "react";

const IfElseEXP1 = () => {
const [isLoggedIn, setIsLoggedIn] = useState(true);

return (
<div>
<h3>if else Example </h3>
<IfElseEXP2 isLoggedIn={isLoggedIn} />
</div>
);
};
const IfElseEXP2 = ({ isLoggedIn }) => {
if (isLoggedIn) {
return <div>Welcome User </div>;
} else {
return <div>You need to login</div>;
}
};

export default IfElseEXP1;
  • Open App.js file and update code as below
import React from "react";
import ReactDOM from "react-dom";
import IfElseEXP1 from "./components/IfElseEXP1";

function App() {
return (
<div className="App">
<IfElseEXP1 />
</div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Output:


No comments:

Post a Comment