Skip to content

Instantly share code, notes, and snippets.

@cailinkless
Created May 16, 2021 18:43
Show Gist options
  • Save cailinkless/02bae44faf36d7e7baaf28835a08e1e6 to your computer and use it in GitHub Desktop.
Save cailinkless/02bae44faf36d7e7baaf28835a08e1e6 to your computer and use it in GitHub Desktop.
Initial Mike Cronin / ITNEXT Clone (Adapted for new use case)
// CreditInputs.js
import React from 'react';
import PropTypes from 'prop-types';
const CreditInputs = ({ idx, creditState, handleCreditChange }) => {
const creditId = `name-${idx}`;
const roleId = `role-${idx}`;
const bioId = `bio-${idx}`;
return (
<div key={`credit-${idx}`}>
<label htmlFor={creditId}>{`Credit #${idx + 1} Name`}</label>
<input
type="text"
name={creditId}
data-idx={idx}
id={creditId}
className="name"
value={creditState[idx].name}
onChange={handleCreditChange}
/>
<label htmlFor={roleId}>Role</label>
<input
type="text"
name={roleId}
data-idx={idx}
id={roleId}
className="role"
value={creditState[idx].role}
onChange={handleCreditChange}
/>
<label htmlFor={bioId}>Bio</label>
<input
type="text"
name={bioId}
data-idx={idx}
id={bioId}
className="bio"
value={creditState[idx].bio}
onChange={handleCreditChange}
/>
</div>
);
};
CreditInputs.propTypes = {
idx: PropTypes.number,
creditState: PropTypes.array,
handleCreditChange: PropTypes.func,
};
export default CreditInputs;
// Form.js
import React, { useState } from 'react';
import CreditInputs from './CreditInputs';
const Form = () => {
const [productionState, setProductionState] = useState({
title: '',
production_note: '',
});
const handleProductionChange = (e) => setProductionState({
...productionState,
[e.target.name]: [e.target.value],
});
const blankCredit = { name: '', role: '', bio: '' };
const [creditState, setCreditState] = useState([
{...blankCredit},
]);
const addCredit = () => {
setCreditState([...creditState, {...blankCredit}]);
};
const handleCreditChange = (e) => {
const updatedCredits = [...creditState];
updatedCredits[e.target.dataset.idx][e.target.className] = e.target.value;
setCreditState(updatedCredits);
};
return (
<form>
<label htmlFor="title">Title</label>
<input type="text" name="title" id="title" value={productionState.title} onChange={handleProductionChange} />
<label htmlFor="production_note">Production Note</label>
<input type="textarea" name="production_note" id="production_note" value={productionState.production_note} onChange={handleProductionChange} />
{
creditState.map((val, idx) => (
<CreditInputs
key={`credit-${idx}`}
idx={idx}
creditState={creditState}
handleCreditChange={handleCreditChange}
/>
))
}
<input type="button" value="Add New Credit" onClick={addCredit}/>
<input type="submit" value="Submit" />
</form>
)
}
export default Form;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment