Issue
I have the following code in my React:
const [property, setProperty] = useState([]);
const [state, setState] = React.useState({ type: "", propertyName: "" });
const handleChange = (e, inputField) => {
setState((prevState) => ({
...prevState,
[inputField]: e.target.value,
}));
};
const handleSubmit = () => {
if (state.type !== "" && state.propertyName !== "") {
const newObject = { type: state.type, propertyName: state.propertyName };
property.push(newObject);
console.log(property);
setState({
type: "",
propertyName: "",
});
}
};
And html:
<div>
<label htmlFor='properties' className='properties-label'>
Properties
</label>
<div className='property-box'>
<input
type='text'
id='type'
value={state.type}
placeholder='Type'
className='type-element'
required
onChange={(e) => handleChange(e, "type")}
></input>
<input
type='text'
id='name'
value={state.propertyName}
className='type-element'
placeholder='Name'
required
onChange={(e) => handleChange(e, "propertyName")}
></input>
<button
className='buttonAccount'
type='submit'
onClick={handleSubmit}
>
Add Property
</button>
</div>
</div>
What I want is when I press the add Property button a new html tag will render on the page(a box or something like that containing the two fields that has been inputted). Can you help me find a way to do that?
Solution
You have to print the elements in your property array. For exmaple:
{
property.map((element) => (
<div key={element.propertyName}>
<span>
{element.type}
</span>
<span>
{element.propertyName}
</span>
</div>
)
}
Answered By - GalAbra
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.