Advertisement
Guest User

Untitled

a guest
Feb 20th, 2020
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. import React, { Component } from 'react';
  2. import './App.css';
  3. import Person from './Person/Person';
  4.  
  5. class App extends Component {
  6. state = {
  7. persons: [
  8. { name: 'Max', age: 28 },
  9. { name: 'Manu', age: 29 },
  10. { name: 'Stephanie', age: 26 }
  11. ],
  12. otherState: 'some other value',
  13. showPerson: false
  14. };
  15.  
  16.  
  17. switchNameHandler = (newName) => {
  18. // console.log('Was clicked!');
  19. // DON'T DO THIS: this.state.persons[0].name = 'Maximilian';
  20. this.setState({
  21. persons: [
  22. {key:"asdqwsd" , name: newName, age: 28 },
  23. {key:"123wdsa" , name: 'Manu', age: 29 },
  24. {key:"dewd121" , name: 'Stephanie', age: 27 }
  25. ]
  26. });
  27. };
  28.  
  29.  
  30. nameChangeHandler = (event , key) => {
  31. const personIndex = this.state.persons.findIndex(p => {
  32. return p.key === key;
  33. });
  34.  
  35. const person = {
  36. ...this.state.persons[personIndex]
  37. };
  38.  
  39. person.name = event.target.value;
  40.  
  41. const persons = [...this.state.persons];
  42. persons[personIndex] = person;
  43.  
  44. this.setState({persons: persons});
  45.  
  46. };
  47.  
  48. deletPersonHandler = (personIndex) => {
  49. const persons = this.state.persons;
  50. persons.splice(personIndex, 1);
  51. this.setState({persons: persons})
  52. }
  53.  
  54. togglePersonHandler = () => {
  55. const doesShow = this.state.showPerson;
  56. this.setState({ showPerson: !doesShow });
  57. }
  58.  
  59. render() {
  60. const style = {
  61. backgroundColor: 'white',
  62. font: 'inherit',
  63. border: '1px solid blue',
  64. padding: '8px',
  65. cursor: 'pointer'
  66. };
  67.  
  68. let persons = null;
  69.  
  70. if (this.state.showPerson) {
  71. persons = (
  72. <div>
  73. {this.state.persons.map((person, index) => {
  74. return <Person
  75. click = {() => this.deletPersonHandler(index)}
  76. name={person.name}
  77. age={person.age}
  78. key={person.key}
  79. changed={(event) => this.nameChangeHandler(event,person.key)}/>
  80. })}
  81. </div>
  82. )
  83. }
  84.  
  85. return (
  86. <div className="App">
  87. <h1>Hi, I'm a React App</h1>
  88. <p>This is really working!</p>
  89. <button
  90. style={style}
  91. onClick={this.togglePersonHandler}>Show / Hide</button>
  92. {persons}
  93. </div>
  94.  
  95.  
  96. );
  97. // return React.createElement('div', {className: 'App'}, React.createElement('h1', null, 'Does this work now?'));
  98. }
  99. }
  100.  
  101. export default App;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement