I am trying to repeat a inputbox when a user submit a data on a textbox. The solution I have able to create following through several sources is as:
a simple input box, inputbox.js
import React from 'react';
const InputBox = () => {
return(
<input type="text" placeholder='Add your content line here ... '/>
);
};
export default InputBox;
component that repeats inputbox on Enter or clicking CreateRecursiveInputBox.js
import React from "react";
import styled from "@emotion/styled";
import InputBox from "./inputbox.js";
// creating a bundler component
const Bundle = styled.div`
display: flex;
flex-direction: row;
justify-content: flex-start;
`;
class CreateRecursiveInputBox extends React.Component {
constructor(props) {
super(props);
this.state = {
values: {
0: ''
},
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(index, value) {
this.setState({
values: {
...this.state.values,
[index]: value
}
});
}
handleSubmit(event) {
event.preventDefault();
this.setState({
values: {
...this.state.values,
[Object.keys(this.state.values).length]: '' // add new empty item to list
}
});
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
{ Object.keys(this.state.values).map( (index) => {
const value = this.state.values[index];
return (<div key={ index }>
<Bundle>
<label> "Name" </label>
<InputBox
value={ value }
onChange={ (event) => this.handleChange( index, event.target.value ) }
/>
{/* <input type="submit"/> */}
<input type="submit" value="Submit"/>
</Bundle>
</div>
);
})}
</form>
</div>
);
}
}
export default CreateRecursiveInputBox;
component to render the textbox and repetitive textbox on UI, App.js
import React, { Component } from 'react';
import CreateRecursiveInputBox from './component/CreateRecursiveInputBox.js';
class App extends React.Component {
render(){
return(
<div>
<CreateRecursiveInputBox/>
</div>
)
}
}
export default App;
I am trying to convert the class based component SubmitCreateRecursiveInputBox.js
to a function based component. But it is not working out so far.