How to remove elements in react?
React task2 with remove text boxes with simple validation for the beginners react learner. Below example for the practice purpose:
App.js
import React, { Component } from 'react';
import './App.css';
import Char from './Char/Char';
import Validation from './Validation/Validation';
class App extends Component {
state = {
inputText: ''
}
inputChangeHandler = (event) => {
this.setState({ inputText: event.target.value })
}
deleteCharHandler = (charIndex) => {
const charText = this.state.inputText.split('');
charText.splice(charIndex, 1);
const updateText = charText.join('');
this.setState({ inputText: updateText });
}
render() {
const charList = this.state.inputText.split('').map((ch, index) => {
return <Char charactor={ch}
key={index}
click={() => this.deleteCharHandler(index)} />
});
return (
<div className="App">
<input type="text" onChange={this.inputChangeHandler} value={this.state.inputText} />
<p>{this.state.inputText}</p>
<Validation inputLenth={this.state.inputText.length} />
<p>{charList}</p>
</div>
);
}
}
export default App;
Validation.js
import React from 'react';
const validation = (props) => {
let validationMessage = 'Text now enough!';
if (props.inputLenth <= 5) {
validationMessage = 'Text Too Short!'
}
return (
<>
{/*
//This is not good practice also we can do this type validation
{props.inputLenth < 5 ?
<p>Text Too Short! </p> :
<p>Text now enough!</p>
} */}
{validationMessage}
</>
)
}
export default validation;
Char.js
import React from 'react';
const char = (props) => {
const style = {
border: '1px solid #0bf',
padding: '5px',
margin: '5px',
display: 'inline-block',
textAlign: 'center'
}
return (
<div style={style} onClick={props.click}>
{props.charactor}
</div>
)
}
export default char;
[Task2]
No comments:
Note: Only a member of this blog may post a comment.