Skip to content

Instantly share code, notes, and snippets.

@ppraksa
Last active July 11, 2019 13:16
Show Gist options
  • Save ppraksa/0289154b0224a4cb5fcbb14bfd6c0e4d to your computer and use it in GitHub Desktop.
Save ppraksa/0289154b0224a4cb5fcbb14bfd6c0e4d to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="5">
<head>
<meta charset="UTF-8">
<title>Pierwszy komponent w React.js</title>
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone/babel.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.13/semantic.min.css">
</head>
<body>
<div id="app"></div>
<script type="text/babel">
const UserList = ({users}) => {
return (
<ul>
{users.map(user => <li key={user}>{user}</li>)}
</ul>
)
};
class Parent extends React.Component {
constructor() {
super();
this.users = [
'Pawel',
'Lukas',
'Paulina',
'Katarzyna',
'Morda'
];
this.state = {
users: this.users,
inputValue: '',
thr: true
};
this.filterUsers = this.filterUsers.bind(this);
}
render() {
return(
<div>
<input type="text" value={this.state.inputValue} onChange={this.filterUsers}/>
<UserList users={this.state.users} />
</div>
);
}
getFilteredUsersForText(text) {
return new Promise(resolve => {
const time = (Math.random() + 1) * 250;
console.log('...waiting');
setTimeout(() => {
const filteredUsers = this.users.filter(user => user.toLowerCase().includes(text.toLowerCase()));
console.log('fetching done');
resolve(filteredUsers);
}, time) ;
});
}
filterUsers(event) {
if(this.state.thr) {
let value = event.target.value,
users;
this.setState({
thr: !this.state.thr
}, () => {
let promise = new Promise((res, rej) => {
setTimeout(() => {
res()
}, 100);
});
promise.then(() => {
this.setState({
inputValue: value,
thr: !this.state.thr
})
}).then(() => {
users = this.getFilteredUsersForText(value).then((users) => {
this.setState({
users
})
});
});
});
} else {
return false;
}
}
}
const App = () => {
return(
<div>
<Parent />
</div>
);
};
ReactDOM.render(<App/>, document.querySelector('#app'));
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment