A React component to render a simple ID generator using a Javascript generator function.
Last active
December 15, 2023 02:55
-
-
Save primaryobjects/8feda357c149e3f228975a6a2641ecc0 to your computer and use it in GitHub Desktop.
ID generator in Javascript, React component https://jsbin.com/goximuyovo/edit?html,css,js,output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width"> | |
<title>JS Bin</title> | |
<script src="https://code.jquery.com/jquery.min.js"></script> | |
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> | |
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> | |
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script> | |
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> | |
<script src='https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser-polyfill.min.js'></script> | |
<title>ID Generator</title> | |
</head> | |
<body> | |
<div class='container'> | |
<h1>ID Generator</h1> | |
<div id='root' /> | |
</div> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// jshint esnext: true | |
// noprotect | |
const idGenerator = function*(init = 1) { | |
let id = init; | |
while (true) { | |
yield id; | |
id++; | |
} | |
}; | |
function IDGenerator(props) { | |
const { useState } = React; | |
const [ id, setId ] = useState(parseInt(props.start) || 1); | |
const [ generator, setGenerator ] = useState(idGenerator(id + 1)); | |
const onGenerate = e => { | |
const value = generator.next().value; | |
setId(value); | |
} | |
return ( | |
<div id='id-generator'> | |
<div id='next-id' class='h1 text-success'>{ id }</div> | |
<button class='btn-lg btn-primary' onClick={ onGenerate }>Generate</button> | |
</div> | |
); | |
} | |
$(function() { | |
ReactDOM.render(<IDGenerator start="1" />, document.getElementById('root')); | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#next-id { | |
border: 1px solid gray; | |
padding: 10px; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment