Wednesday 15 March 2023

React baby Exercises

Ex 1. Simple Displaying A MESSAGE


npm create vite

√ Project name: ... ex1

√ Select a framework: » React

√ Select a variant: » TypeScript

Scaffolding project in C:\Users\rmcme\ex1...

Done. Now run:

cd ex1

npm install

npm run dev

code . to invoke vs code ide


delete the contents of index.css

Replace the contents of App.tsx

with the following

function App() {
  return <h1>Hello React World</h1>;
}
export default App;


in vs code terminal window:

npm install

npm run dev

it will display URL. Open that URL.Will look similar to the given window


Super! We have done the First React !!!


Ex 2. Simple Displaying Array of Names


Replace the contents of App.tsx with


// EX 2
function App() {
  const ceos = [
    { name: "Elon Musk", id: "1" },
    { name: "Bill Gates", id: "2" },
    { name: "Steve Jobs", id: "3" },
  ];

  const ceosNames = ceos.map((ceo) => <li key={ceo.id}>{ceo.name}</li>);

  return (
    <>
      <h3>CEO names</h3>
      <ul>{ceosNames}</ul>
    </>
  );
}

export default App;


You will see browser output similar to the below




Ex 3. Simple Show/Hide DOM Element

Replace the contents of App.tsx with 

//EX 3

import { useState } from "react";
function App() {
  const [show, setShow] = useState(true);
  return (
    <>
      <button onClick={() => setShow(!show)}>
        {show ? "Hide Element below" : "Show Element Below"}
      </button>
      {show && <div>Toggle Challenge </div>}
    </>
  );
}

export default App;



The browser output will be similar to:




once you click the Hide element Button, you can see the browser output similar to:



Ex 4. Data Binding 2 Ways

Replace the contents of App.tsx with 

// EX 4
import { useState } from "react";

function App() {
  const [value, setValue] = useState("");

  return (
    <>
      <input
        type="text"
        placeholder="Enter Text"
        value={value}
        onChange={(e) => setValue(e.target.value)}
      />
      <p>{value}</p>
    </>
  );
}

export default App;

The browser output will be:


 
Once you entered text in text box, the browser output will be 





Ex 5. Enable Button Element 

Replace the contents of App.tsx with 

// EX 5
import { useState } from "react";

function App() {
  const [value, setValue] = useState("");

  return (
    <>
      <h3>No Text No Submit, If "Text" Submit Challenge</h3>
      <input type="text" onChange={(e) => setValue(e.target.value)} />
      <button disabled={value.length < 1}>Submit</button>
    </>
  );
}

export default App;

The browser output will be:




 
Once you entered text in text box, the submit button will be enabled  











No comments:

Post a Comment

Making Prompts for Profile Web Site

  Prompt: Can you create prompt to craft better draft in a given topic. Response: Sure! Could you please specify the topic for which you...