Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component } from 'react';
- import './App.css';
- import Person from './Person/Person';
- class App extends Component {
- state = {
- persons: [
- { name: 'Max', age: 28 },
- { name: 'Manu', age: 29 },
- { name: 'Stephanie', age: 26 }
- ],
- otherState: 'some other value',
- showPerson: false
- };
- switchNameHandler = (newName) => {
- // console.log('Was clicked!');
- // DON'T DO THIS: this.state.persons[0].name = 'Maximilian';
- this.setState({
- persons: [
- {key:"asdqwsd" , name: newName, age: 28 },
- {key:"123wdsa" , name: 'Manu', age: 29 },
- {key:"dewd121" , name: 'Stephanie', age: 27 }
- ]
- });
- };
- nameChangeHandler = (event , key) => {
- const personIndex = this.state.persons.findIndex(p => {
- return p.key === key;
- });
- const person = {
- ...this.state.persons[personIndex]
- };
- person.name = event.target.value;
- const persons = [...this.state.persons];
- persons[personIndex] = person;
- this.setState({persons: persons});
- };
- deletPersonHandler = (personIndex) => {
- const persons = this.state.persons;
- persons.splice(personIndex, 1);
- this.setState({persons: persons})
- }
- togglePersonHandler = () => {
- const doesShow = this.state.showPerson;
- this.setState({ showPerson: !doesShow });
- }
- render() {
- const style = {
- backgroundColor: 'white',
- font: 'inherit',
- border: '1px solid blue',
- padding: '8px',
- cursor: 'pointer'
- };
- let persons = null;
- if (this.state.showPerson) {
- persons = (
- <div>
- {this.state.persons.map((person, index) => {
- return <Person
- click = {() => this.deletPersonHandler(index)}
- name={person.name}
- age={person.age}
- key={person.key}
- changed={(event) => this.nameChangeHandler(event,person.key)}/>
- })}
- </div>
- )
- }
- return (
- <div className="App">
- <h1>Hi, I'm a React App</h1>
- <p>This is really working!</p>
- <button
- style={style}
- onClick={this.togglePersonHandler}>Show / Hide</button>
- {persons}
- </div>
- );
- // return React.createElement('div', {className: 'App'}, React.createElement('h1', null, 'Does this work now?'));
- }
- }
- export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement