<main></main>
.valid {
border-bottom: 4px solid green;
}
.invalid {
border-bottom: 4px solid red;
}
.ib {
display: inline-block;
}
class Textbox extends React.Component {
constructor(props) {
super(props);
this.state = { text: props.text, changed: false };
}
static getDerivedStateFromProps(props, state) {
if (state.changed) {
return null;
} else {
return { text: props.text };
}
}
setText(newText) {
this.setState({ text: newText, changed: true });
}
render() {
const initialText = this.props.text;
const { text } = this.state;
const cls = (text === initialText ? 'valid' : 'invalid');
return (
<div className='ib'>
<input
type='text'
value={text}
className={cls}
onChange={(e) => this.setText(e.target.value)}
/>
<p>{this.props.text}</p>
</div>
)
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = { text: 'hello world' };
}
randomizeText() {
const texts = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'];
this.setState({ text: texts[Math.floor(Math.random() * texts.length)]});
}
render() {
const {text} = this.state;
return (
<div>
<div>
<button onClick={() => this.randomizeText()}>Change Text</button>
</div>
<Textbox text={text} />
<Textbox text={text} />
<Textbox text={text} />
<Textbox text={text} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('main'));
View Compiled
This Pen doesn't use any external CSS resources.