I have a component which takes input and adds them to a list and displays them:
import React, {Component} from 'react'
import {
Form,
Col,
Label,
FormGroup,
Button,
Alert,
Input,
Row,
} from 'reactstrap'
export default class NewSubreddit extends Component {
constructor(props) {
super(props)
this.state = {rules: []}
}
addRule() {
const rule = document.getElementById('new-rule').value
if(rule) {
this.setState(prev => ({
rules: prev.rules.concat(rule),
}))
}
console.log(this.state)
}
deleteRule(e) {
e.preventDefault()
console.log(e.target)
// this.setState(prev => ({
// }))
}
render() {
return (
<React.Fragment>
<Form>
<FormGroup row>
<Label sm={2}>Rules</Label>
<Col sm={10}>
<Row>
<Col>
<Input id='new-rule' type='text' placeholder='Add a rule that members of this community should follow!'/>
</Col>
<Col>
<Button onClick={() => this.addRule()}>ADD RULE</Button>
</Col>
</Row>
</Col>
</FormGroup>
<FormGroup row>
<Col>
{this.state.rules.map((rule) =>
<Alert key={rule} isOpen={true} toggle={this.deleteRule}>{rule}</Alert>
)}
</Col>
</FormGroup>
</Form>
</React.Fragment>
)
}
}
So, I am able to add the rules to the array rules present in state.
There are 2 things that I need to do here:
- Restrict to create only fixed number of rules (say 4).
- Delete a Rule by toggling the alert.
I tried to do the deletion in deleteRule function by trying to access event.target.value but it is undefined!!