React: Evitando Anti-patterns

bind() e Funções em Componentes

import React from "react";export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
name: ""
};
this.updateValue = this.updateValue.bind(this);
}
updateValue(e) {
this.setState({
name: e.target.value
});
}
render() {
return (
<>
<form>
<input onChange={this.updateValue} value={this.state.name} />
</form>
<p>{this.state.name}</p>
</>
);
}
}
this.updateValue = this.updateValue.bind(this);
<input onChange={this.updateValue.bind(this)} value={this.state.name} />

Extra: bind em Arrow Functions x bind no construtor

Class Click extends react.Component {
constructor(props) {
super(props)
this.clickEvent = this.clickEvent.bind(this);
}

render = () => (
<button onClick={this.clickEvent}>Click Me</button>
)

clickEvent() {console.log(this)} // 'this' refers to the class
}
import React from 'react';
class MyComponent extends React.Component {
constructor(props) {
super(props)
}

clickHandler = () => {
console.log( this )
}

render() {
return <button onClick={this.clickHandler}>Click Me</button>
}
}
const spy = jest.spyOn(MyComponent.prototype, 'clickHandler');
// ...
expect(spy).toHaveBeenCalled();

Esquecendo a prop key ou usando indexes na prop key

import React from "react";
import { v4 as uuidv4 } from "uuid";
const arr = [
{
fruit: "apple",
id: uuidv4()
},
{
fruit: "orange",
id: uuidv4()
},
{
fruit: "grape",
id: uuidv4()
}
];
export default function App() {
return (
<div className="App">
{arr.map(a => (
<p key={arr.id}>{a.fruit}</p>
))}
</div>
);
}

Nomes de Componentes

import React from "react";const foo = () => <p>foo</p>;export default function App() {
return (
<div className="App">
<foo />
</div>
);
}
import React from "react";const Foo = () => <p>foo</p>;export default function App() {
return (
<div className="App">
<Foo />
</div>
);
}

Fechar cada elemento

import React from "react";const Foo = () => <p>foo</p>export default function App() {
return (
<div className="App">
<Foo>
</div>
);
}
<Foo>
import React from "react";const Foo = () => <p>foo</p>;export default function App() {
return (
<div className="App">
<Foo />
</div>
);
}

Conclusão

Referências

Créditos

Software Engineer | Front-end Specialist @ Grover (https://rubenmarcus.dev)

Software Engineer | Front-end Specialist @ Grover (https://rubenmarcus.dev)