-
Notifications
You must be signed in to change notification settings - Fork 11
Forms in React
HTML form elements work a little bit differently from other DOM elements in React, because form elements naturally keep some internal state. For example, this form in plain HTML accepts a single name:
<form>
<label>
Name:
<input type="text" name="name" />
</label>
<input type="submit" value="Submit" />
</form>
This form has the default HTML form behavior of browsing to a new page when the user submits the form. If you want this behavior in React, it just works. But in most cases, it’s convenient to have a JavaScript function that handles the submission of the form and has access to the data that the user entered into the form. The standard way to achieve this is with a technique called “controlled components”.
In HTML, form elements such as <input>
, <textarea>
, and <select>
typically maintain their own state and update it based on user input. In React, mutable state is typically kept in the state property of components, and only updated with setState()
.
We can combine the two by making the React state be the “single source of truth”. Then the React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled component”.
For example, if we want to make the previous example log the name when it is submitted, we can write the form as a controlled component:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) { this.setState({value: event.target.value}); }
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}> <label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} /> </label>
<input type="submit" value="Submit" />
</form>
);
}
}
Since the value
attribute is set on our form element, the displayed value will always be this.state.value
, making the React state the source of truth. Since handleChange
runs on every keystroke to update the React state, the displayed value will update as the user types.
With a controlled component, the input’s value is always driven by the React state. While this means you have to type a bit more code, you can now pass the value to other UI elements too, or reset it from other event handlers.
In HTML, a <textarea>
element defines its text by its children:
<textarea>
Hello there, this is some text in a text area
</textarea>
In React, a <textarea>
uses a value
attribute instead. This way, a form using a <textarea>
can be written very similarly to a form that uses a single-line input:
class EssayForm extends React.Component {
constructor(props) {
super(props);
this.state = { value: 'Please write an essay about your favorite DOM element.' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) { this.setState({value: event.target.value}); }
handleSubmit(event) {
alert('An essay was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Essay:
<textarea value={this.state.value} onChange={this.handleChange} /> </label>
<input type="submit" value="Submit" />
</form>
);
}
}
Notice that this.state.value
is initialized in the constructor, so that the text area starts off with some text in it.
In HTML, <select>
creates a drop-down list. For example, this HTML creates a drop-down list of flavors:
<select>
<option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option selected value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
Note that the Coconut option is initially selected, because of the selected
attribute. React, instead of using this selected
attribute, uses a value
attribute on the root select
tag. This is more convenient in a controlled component because you only need to update it in one place. For example:
class FlavorForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'coconut'};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) { this.setState({value: event.target.value}); }
handleSubmit(event) {
alert('Your favorite flavor is: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Pick your favorite flavor:
<select value={this.state.value} onChange={this.handleChange}> <option value="grapefruit">Grapefruit</option>
<option value="lime">Lime</option>
<option value="coconut">Coconut</option>
<option value="mango">Mango</option>
</select>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
Overall, this makes it so that <input type="text">
, <textarea>
, and <select>
all work very similarly - they all accept a value
attribute that you can use to implement a controlled component.
Note
You can pass an array into the
value
attribute, allowing you to select multiple options in aselect
tag:<select multiple={true} value={['B', 'C']}>
In HTML, an <input type="file">
lets the user choose one or more files from their device storage to be uploaded to a server or manipulated by JavaScript via the File API.
Because its value is read-only, it is an uncontrolled component in React. It is discussed together with other uncontrolled components later in the documentation.
When you need to handle multiple controlled input
elements, you can add a name
attribute to each element and let the handler function choose what to do based on the value of event.target.name
.
For example:
class Reservation extends React.Component {
constructor(props) {
super(props);
this.state = {
isGoing: true,
numberOfGuests: 2
};
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value });
}
render() {
return (
<form>
<label>
Is going:
<input
name="isGoing" type="checkbox"
checked={this.state.isGoing}
onChange={this.handleInputChange} />
</label>
<br />
<label>
Number of guests:
<input
name="numberOfGuests" type="number"
value={this.state.numberOfGuests}
onChange={this.handleInputChange} />
</label>
</form>
);
}
}
Note how we used the ES6 computed property name syntax to update the state key corresponding to the given input name:
this.setState({
[name]: value});
It is equivalent to this ES5 code:
var partialState = {};
partialState[name] = value;this.setState(partialState);
Also, since setState()
automatically merges a partial state into the current state, we only needed to call it with the changed parts.
Specifying the value prop on a controlled component prevents the user from changing the input unless you desire so. If you’ve specified a value
but the input is still editable, you may have accidentally set value
to undefined
or null
.
The following code demonstrates this. (The input is locked at first but becomes editable after a short delay.)
ReactDOM.render(<input value="hi" />, mountNode);
setTimeout(function() {
ReactDOM.render(<input value={null} />, mountNode);
}, 1000);
It can sometimes be tedious to use controlled components, because you need to write an event handler for every way your data can change and pipe all of the input state through a React component. This can become particularly annoying when you are converting a preexisting codebase to React, or integrating a React application with a non-React library. In these situations, you might want to check out uncontrolled components, an alternative technique for implementing input forms.
If you’re looking for a complete solution including validation, keeping track of the visited fields, and handling form submission, Formik is one of the popular choices. However, it is built on the same principles of controlled components and managing state — so don’t neglect to learn them.
Languages |
|
| Libraries |
|
| Frameworks |
|
| Databases |
|
| Testing |
|
| Other |
|
- GitHub
- Gitlab
- Bitbucket
- code pen
- Glitch
- Replit
- Redit
- runkit
- stack-exchange
- Netlify
- Medium
- webcomponents.dev
- npm
- Upwork
- AngelList
- Quora
- dev.to
- Observable Notebooks
- Notation
- StackShare
- Plunk
- Dribble
➤ Blog:
I write articles for:
![medium](./medium. PNG)
About Me
![skills](./skills. PNG)
-
🔭 Contract Web Development Relational Concepts
-
🌱 I'm currently learning React/Redux, Python, Java, Express, jQuery
-
👯 I'm looking to collaborate on Any web audio or open source educational tools.
-
🤝 I'm looking for help with Learning React
-
👨💻 All of my projects are available at https://bgoonz.github.io/
-
📝 I regularly write articles on medium && Web-Dev-Resource-Hub
-
💬 Ask me about Anything:
-
📫 How to reach me bryan.guner@gmail.com
-
⚡ Fun fact I played Bamboozle Music Festival at the Meadowlands Stadium Complex when I was 14.
A Random Walk Down Wall Street
Hitchhiker's Guide To The Galaxy
Designing recording software/hardware and using it
Try harder and listen to your parents more (the latter bit of advice would be almost certain to fall on deaf ears lol)
I built a platform that listens to a guitarist's performance and automatically triggers guitar effects at the appropriate time in the song.
Is it to basic to say Tesla... I know they're prevalent now but I've been an avid fan since as early as 2012.
Having really good ideas and forgetting them moments later.
A text
Creating things that change my every day life.
Modern Physics... almost changed my major after that class... but at the end of the day engineering was a much more fiscally secure avenue.
Learned to code ... and sing
*Disclaimer: The following wisdom is very cliche ... but... "Be the change that you wish to see in the world."
― Mahatma Gandhi
🤖 My Programming Stats:
![waka1](https://github.com/bgoonz/bgoonz/blob/master/langs. PNG)
![waka2](https://github.com/bgoonz/bgoonz/blob/master/waka. PNG)
Resume
Programming** Languages:** | JavaScript ES-6, NodeJS, React, HTML5, CSS3, SCSS, Bash Shell, Excel, SQL, NoSQL, MATLAB, Python, C++ |
---|---|
Databases: | PostgreSQL, MongoDB |
Cloud: | Docker, AWS, Google App Engine, Netlify, Digital Ocean, Heroku, Azure Cloud Services |
OS: | Linux, Windows (WSL), IOS |
Agile: | GitHub, BitBucket, Jira, Confluence |
IDEs: | VSCode, Visual Studio, Atom, Code Blocks, Sublime Text 3, Brackets |
Relational Concepts: Hallandale Beach, FL | March 2020 - Present |
---|---|
Front End Web Developer | |
- Responsible for front-end development for a custom real estate application which provides sophisticated and fully customizable filtering to allow investors and real estate professionals to narrow in on exact search targets.
- Designed mock-up screens, wireframes, and workflows for intuitive user experience.
- Migrated existing multi-page user experience into singular page interfaces using React components.
- Participated in every stage of the design from conception through development and iterative improvement.
- Produced user stories and internal documentation for future site development and maintenance.
- Implemented modern frameworks including Bootstrap and Font-Awesome to give the site an aesthetic overhaul.
- Managed all test deployments using a combination of Digital Ocean and Netlify.
- Produced unit tests using a combination of Mocha and Chai.
- Injected Google Analytics to capture pertinent usage data to produce an insightful dashboard experience.
Environment: | JavaScript, JQuery, React, HTML5 & CSS, Bootstrap, DOJO, Google Cloud, Bash Script |
---|
Cembre: Edison, NJ | Nov 2019 – Mar 2020 |
---|---|
Product Development Engineer | |
- Converted client' s product needs into technical specs to be sent to the development team in Italy.
- Reorganized internal file server structure.
- Conducted remote / in person system integration and product demonstrations.
- Presided over internal and end user software trainings in addition to producing the corresponding documentation.
- Served as the primary point of contact for troubleshooting railroad hardware and software in the North America.
Environment: | Excel, AutoCAD, PowerPoint, Word |
---|
**B. S. Electrical Engineering, TCNJ, ** Ewing NJ | 2014 – 2019 |
---|
Capstone Project – Team Lead
- Successfully completed and delivered a platform to digitize a guitar signal and perform filtering before executing frequency & time domain analysis to track a current performance against prerecorded performance.
- Implemented the Dynamic Time Warping algorithm in C++ and Python to autonomously activate or adjust guitar effect at multiple pre-designated section of performance.
Environment: | C++, Python, MATLAB, PureData |
---|
My Projects
<tr>
<th>Project Name</th>
<th>Skills used</th>
<th>Description</th>
</tr>
<tr>
<td><a href='https://web-dev-resource-hub.netlify.app/'>Web-Dev-Resource-Hub (blog)</a></td>
<td>Html, Css, javascript, Python, jQuery, React, FireBase, AWS S3, Netlify, Heroku, NodeJS, PostgreSQL, C++, Web Audio API</td>
<td>My blog site contains my resource sharing and blog site ... centered mostly on web development and just a bit of audio production / generally nerdy things I find interesting.</td>
</tr>
<tr>
<td><a href='https://project-showcase-bgoonz.netlify.app/'>Dynamic Guitar Effects Triggering Using A Modified Dynamic Time Warping Algorithm</a></td>
<td>C, C++, Python, Java, Pure Data, Matlab</td>
<td>Successfully completed and delivered a platform to digitize a guitar signal and perform filtering before executing frequency & time domain analysis to track a current performance against prerecorded performance.Implemented the Dynamic Time Warping algorithm in C++ and Python to autonomously activate or adjust guitar effect at multiple pre-designated section of performance.</td>
</tr>
<tr>
<td><a href="https://trusting-dijkstra-4d3b17.netlify.app/">Data Structures & Algorithms Interactive Learning Site</a></td>
<td>HTML, CSS, Javascript, Python, Java, jQuery, Repl.it-Database API</td>
<td>A interactive and comprehensive guide and learning tool for DataStructures and Algorithms ... concentrated on JS but with some examples in Python, C++ and Java as well</td>
</tr>
<tr>
<td><a href='https://mihirbegmusic.netlify.app/'>MihirBeg.com</a></td>
<td>Html, Css, Javascript, Bootstrap, FontAwesome, jQuery</td>
<td>A responsive and mobile friendly content promotion site for an Audio Engineer to engage with fans and potential clients</td>
</tr>
<tr>
<td><a href='https://tetris42.netlify.app/'>Tetris-JS</a></td>
<td>Html, Css, Javascript</td>
<td>The classic game of tetris implemented in plain javascipt and styled with a retro-futureistic theme</td>
</tr>
<tr>
<td><a href="https://githtmlpreview.netlify.app/">Git Html Preview Tool</a></td>
<td>Git, Javascript, CSS3, HTML5, Bootstrap, BitBucket</td>
<td>Loads HTML using CORS proxy, then process all links, frames, scripts and styles, and load each of them using CORS proxy, so they can be evaluated by the browser.</td>
</tr>
<tr>
<td><a href='https://project-showcase-bgoonz.netlify.app/'>Mini Project Showcase</a></td>
<td>HTML, HTML5, CSS, CSS3, Javascript, jQuery</td>
<td>add songs and play music, it also uses to store data in INDEXEDB Database by which we can play songs, if we not clear the catch then song will remain stored in database.</td>
</tr>
---
the method string.replaceAll(search, replaceWith) replaces all appearances of search string with replaceWith.
const str = 'this is a JSsnippets example';
const updatedStr = str.replace('example', 'snippet'); // 'this is a JSsnippets snippet'
The tricky part is that replace method replaces only the very first match of the substring we have passed:
const str = 'this is a JSsnippets example and examples are great';
const updatedStr = str.replace('example', 'snippet'); //'this is a JSsnippets snippet and examples are great'
In order to go through this, we need to use a global regexp instead:
const str = 'this is a JSsnippets example and examples are great';
const updatedStr = str.replace(/example/g, 'snippet'); //'this is a JSsnippets snippet and snippets are greatr'
but now we have new friend in town, replaceAll
const str = 'this is a JSsnippets example and examples are great';
const updatedStr = str.replaceAll('example', 'snippet'); //'this is a JSsnippets snippet and snippets are greatr'
def fib_iter(n):
if n == 0:
return 0
if n == 1:
return 1
p0 = 0
p1 = 1
for i in range(n-1):
next_val = p0 + p1
p0 = p1
p1 = next_val
return next_val
for i in range(10):
print(f'{i}: {fib_iter(i)}')
def quicksort(l):
# One of our base cases is an empty list or list with one element
if len(l) == 0 or len(l) == 1:
return l
# If we have a left list, a pivot point and a right list...
# assigns the return values of the partition() function
left, pivot, right = partition(l)
# Our sorted list looks like left + pivot + right, but sorted.
# Pivot has to be in brackets to be a list, so python can concatenate all the elements to a single list
return quicksort(left) + [pivot] + quicksort(right)
print(quicksort([]))
print(quicksort([1]))
print(quicksort([1,2]))
print(quicksort([2,1]))
print(quicksort([2,2]))
print(quicksort([5,3,9,4,8,1,7]))
print(quicksort([1,2,3,4,5,6,7]))
print(quicksort([9,8,7,6,5,4,3,2,1]))
See Older Snippets!
will replace any spaces in file names with an underscore!
for file in *; do mv "$file" `echo $file | tr ' ' '_'` ; done
## TAKING IT A STEP FURTHER:
# Let's do it recursivley:
function RecurseDirs ()
{
oldIFS=$IFS
IFS=$'\n'
for f in "$@"
do
# YOUR CODE HERE!
[![-----------------------------------------------------](https://raw.githubusercontent.com/andreasbm/readme/master/assets/lines/colored.png)]
for file in *; do mv "$file" `echo $file | tr ' ' '_'` ; done
if [[ -d "${f}" ]]; then
cd "${f}"
RecurseDirs $(ls -1 ".")
cd ..
fi
done
IFS=$oldIFS
}
RecurseDirs "./"
Language: Javascript/Jquery
In combination with the script tag : <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> , this snippet will add a copy to clipboard button to all of your embedded
blocks.
$(document).ready(function() {
$('code, pre').append('<span class="command-copy" ><i class="fa fa-clipboard" aria-hidden="true"></i></span>');
$('code span.command-copy').click(function(e) {
var text = $(this).parent().text().trim(); //.text();
var copyHex = document.createElement('input');
copyHex.value = text
document.body.appendChild(copyHex);
copyHex.select();
document.execCommand('copy');
console.log(copyHex.value)
document.body.removeChild(copyHex);
});
$('pre span.command-copy').click(function(e) {
var text = $(this).parent().text().trim();
var copyHex = document.createElement('input');
copyHex.value = text
document.body.appendChild(copyHex);
copyHex.select();
document.execCommand('copy');
console.log(copyHex.value)
document.body.removeChild(copyHex);
});
})
//APPEND-DIR.js
const fs = require('fs');
let cat = require('child_process').execSync('cat *').toString('UTF-8');
fs.writeFile('output.md', cat, (err) => {
if (err) throw err;
});
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// Result: will return true if user is on an Apple device
/*
function named intersection(firstArr) that takes in an array and
returns a function.
When the function returned by intersection is invoked
passing in an array (secondArr) it returns a new array containing the elements
common to both firstArr and secondArr.
*/
function intersection(firstArr) {
return (secondArr) => {
let common = [];
for (let i = 0; i < firstArr.length; i++) {
let el = firstArr[i];
if (secondArr.indexOf(el) > -1) {
common.push(el);
}
}
return common;
};
}
let abc = intersection(["a", "b", "c"]); // returns a function
console.log(abc(["b", "d", "c"])); // returns [ 'b', 'c' ]
let fame = intersection(["f", "a", "m", "e"]); // returns a function
console.log(fame(["a", "f", "z", "b"])); // returns [ 'f', 'a' ]
/*
First is recurSum(arr, start) which returns the sum of the elements of arr from the index start till the very end.
Second is partrecurSum() that recursively concatenates the required sum into an array and when we reach the end of the array, it returns the concatenated array.
*/
//arr.length -1 = 5
// arr [ 1, 7, 12, 6, 5, 10 ]
// ind [ 0 1 2 3 4 5 ]
// ↟ ↟
// start end
function recurSum(arr, start = 0, sum = 0) {
if (start < arr.length) {
return recurSum(arr, start + 1, sum + arr[start]);
};
return sum;
}
function rPartSumsArr(arr, partSum = [], start = 0, end = arr.length - 1) {
if (start <= end) {
return rPartSumsArr(arr, partSum.concat(recurSum(arr, start)), ++start, end);
};
return partSum.reverse();
}
console.log('------------------------------------------------rPartSumArr------------------------------------------------')
console.log('rPartSumsArr(arr)=[ 1, 1, 5, 2, 6, 10 ]: ', rPartSumsArr(arr));
console.log('rPartSumsArr(arr1)=[ 1, 7, 12, 6, 5, 10 ]: ', rPartSumsArr(arr1));
console.log('------------------------------------------------rPartSumArr------------------------------------------------')
/*
------------------------------------------------rPartSumArr------------------------------------------------
rPartSumsArr(arr)=[ 1, 1, 5, 2, 6, 10 ]: [ 10, 16, 18, 23, 24, 25 ]
rPartSumsArr(arr1)=[ 1, 7, 12, 6, 5, 10 ]: [ 10, 15, 21, 33, 40, 41 ]
------------------------------------------------rPartSumArr------------------------------------------------
*/
function camelToKebab(value) {
return value.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
}
function camel(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function(match, index) {
if (+match === 0) return ""; // or if (/\s+/.test(match)) for white spaces
return index === 0 ? match.toLowerCase() : match.toUpperCase();
});
}
function addTwoNumbers(l1, l2) {
let result = new ListNode(0)
let currentNode = result
let carryOver = 0
while (l1 != null || l2 != null) {
let v1 = 0
let v2 = 0
if (l1 != null) v1 = l1.val
if (l2 != null) v2 = l2.val
let sum = v1 + v2 + carryOver
carryOver = Math.floor(sum / 10)
sum = sum % 10
currentNode.next = new ListNode(sum)
currentNode = currentNode.next
if (l1 != null) l1 = l1.next
if (l2 != null) l2 = l2.next
}
if (carryOver > 0) {
currentNode.next = new ListNode(carryOver)
}
return result.next
};
//Function to test if a character is alpha numeric that is faster than a regular
//expression in JavaScript
let isAlphaNumeric = (char) => {
char = char.toString();
let id = char.charCodeAt(0);
if (
!(id > 47 && id < 58) && // if not numeric(0-9)
!(id > 64 && id < 91) && // if not letter(A-Z)
!(id > 96 && id < 123) // if not letter(a-z)
) {
return false;
}
return true;
};
console.log(isAlphaNumeric("A")); //true
console.log(isAlphaNumeric(2)); //true
console.log(isAlphaNumeric("z")); //true
console.log(isAlphaNumeric(" ")); //false
console.log(isAlphaNumeric("!")); //false
function replaceWords(str, before, after) {
if (/^[A-Z]/.test(before)) {
after = after[0].toUpperCase() + after.substring(1)
} else {
after = after[0].toLowerCase() + after.substring(1)
}
return str.replace(before, after)
}
console.log(replaceWords("Let us go to the store", "store", "mall")) //"Let us go to the mall"
console.log(replaceWords("He is Sleeping on the couch", "Sleeping", "sitting")) //"He is Sitting on the couch"
console.log(replaceWords("His name is Tom", "Tom", "john"))
//"His name is John"
/*Simple Function to flatten an array into a single layer */
const flatten = (array) =>
array.reduce(
(accum, ele) => accum.concat(Array.isArray(ele) ? flatten(ele) : ele),
[]
);
const isWeekday = (date) => date.getDay() % 6 !== 0;
console.log(isWeekday(new Date(2021, 0, 11)));
// Result: true (Monday)
console.log(isWeekday(new Date(2021, 0, 10)));
// Result: false (Sunday)
function longestCommonPrefix(strs) {
let prefix = ''
if (strs.length === 0) return prefix
for (let i = 0; i < strs[0].length; i++) {
const character = strs[0][i]
for (let j = 0; j < strs.length; j++) {
if (strs[j][i] !== character) return prefix
}
prefix = prefix + character
}
return prefix
}