Skip to content

Instantly share code, notes, and snippets.

@iamparthaonline
Created October 28, 2022 14:26
Show Gist options
  • Select an option

  • Save iamparthaonline/f72e3fe4ae1d6fbc44e486c66f6d3960 to your computer and use it in GitHub Desktop.

Select an option

Save iamparthaonline/f72e3fe4ae1d6fbc44e486c66f6d3960 to your computer and use it in GitHub Desktop.
/**
* Handling Forms and different events
* Conditional rendering
* Looping in react
*/
// import "./style.css";
import { useState, createRef } from "react";
const RenderResult = (props) => {
const { showResult, firstName, removeHandler } = props;
const arrayOfCharacters = firstName.split("");
if (showResult) {
return (
<div className="result">
Name - {firstName.toUpperCase()}
<br />
Length - {firstName.length}
<br />
<button
onClick={() => {
removeHandler();
}}
>
Remove Section
</button>
<div>
<ul>
{arrayOfCharacters.map((character, index) => (
<li key={index}>{character}</li>
))}
</ul>
</div>
</div>
);
}
return <div></div>;
};
const FormComponent = () => {
const [firstName, setFirstName] = useState("");
const [showResult, setShowResult] = useState(false);
const inputRef = createRef();
const redDiv = createRef();
return (
<div className="form-container">
<h2>Form Component</h2>
<form
onSubmit={(event) => {
console.log("hello submit");
event.stopPropagation();
event.preventDefault();
setShowResult(true);
}}
>
<label htmlFor="first-name">
Name:
<input
value={firstName}
onChange={(event) => {
setFirstName(event.target.value.toUpperCase());
}}
name="first-name"
type="text"
/>
</label>
<input type="text" ref={inputRef} />
<span
onClick={() => {
console.log(" Value --> ", inputRef.current.value);
}}
>
Get Value
</span>
<div
id="red-div"
ref={redDiv}
style={{
backgroundColor: "red",
height: "100px",
width: "100px",
margin: "50px",
}}
></div>
<span
onClick={() => {
redDiv.current.style.background = "green";
}}
>
{" "}
Change Color{" "}
</span>
<button type="submit">Submit</button>
<RenderResult
firstName={firstName}
showResult={showResult}
removeHandler={() => {
setShowResult(false);
}}
/>
</form>
</div>
);
};
export default FormComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment