Skip to main content

4.12 Practice - Solution

Folder Structure


├── src
│   └── App.js

├── Validation
│   └── Validation.js

├── Char
│   └── Char.js

App.js

github.com: Practice-4-1 (branch), last commit
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 = {
userInput: "",
};
inputChangeHandler = (event) => {
this.setState({
userInput: event.target.value,
});
};
deleteCharHandler = (charIndex) => {
const text = this.state.userInput.split("");
text.splice(charIndex, 1);
const updatedText = text.join("");
this.setState({
userInput: updatedText,
});
};
render() {
const userText = this.state.userInput.split("").map((ch, index) => {
return (
<Char
char={ch}
key={index}
clicked={() => this.deleteCharHandler(index)}
/>
);
});
return (
<div className="App">
<input
type="text"
value={this.state.userInput}
onChange={(event) => this.inputChangeHandler(event)}
/>
<p>{this.state.userInput.length}</p>
<Validation inputLength={this.state.userInput.length} />
{userText}
</div>
);
}
}

export default App;

Validation.js

Validation.js
import React from "react";

const validation = (props) => {
let validationMessage = "Text too short";
if (props.textLength > 5) validationMessage = "Text long enough";
return (
<div>
<p>{validationMessage}</p>
</div>
);
};

export default validation;

Char.js

Char.js
import React from "react";

const char = (props) => {
const style = {
display: "inline-block",
padding: "16px",
textAlign: "center",
margin: "16px",
border: "1px solid #ccc",
cursor: "pointer",
};
return (
<div style={style} onClick={props.clicked}>
{props.char}
</div>
);
};

export default char;