const [showNotes, setShowNotes] = useState(false);
const generateNotes = () => {
setShowNotes(true);
<TextField id="notesField" label="Add your note here" variant="outlined"/>
};
<div style = {{ display: 'flex', width: '300px', justifyContent: 'space-between' }}>
<Button id="note" onClick={generateNotes} variant="contained" component="label" style = {{ backgroundColor: '#3f78b5', flex: '50px', width: '122px', height: '38px',
borderRadius: '8px', left: '388px', position: 'absolute' }}>
Add Note
</Button>
</div>
I created a useState variable and initialized it to false. Then, I created a function that would set it to true and create the textfield. Then when the button is clicked it should display the textfield but that is not happening. I realize I did not set the showNotes variable anywhere but I am not sure on what to set to that.
you can do this by having an array that the button appends some text to, and react will create a TextField component for every item, example:
const [notes, setNotes] = useState([]);
const generateNotes = () => {
notes.push('some label');
setNotes([ ...notes ]);
};
return (
<div>
<Button id="note" onClick={generateNotes}></Button>
{
notes.map((item, index)=>{
return <TextField key={index} label={item)/>
}
}
</div>
)
You cannnot render TextField inside a callback, it should be from your component return.You can create a counter to increment the number of input fields and render only if count is greater than zero.
const [inputFieldCount, setInputFieldCount] = useState(0);
const generateNotes = () => {
setInputFieldCount((count) => count + 1);
};
return (
<div
style={{ display: "flex", width: "300px", justifyContent: "space-between" }}
>
<Button onClick={generateNotes}>Add Note</Button>
{inputFieldCount > 0 && Array.from({ length: inputFieldCount }, (_, index) => (
<TextField
key={index}
id="notesField"
label="Add your note here"
variant="outlined"
/>
))}
</div>
);
The second argument from Array.from is a map function to iterate over the array count.