DEV Community

Jasterix
Jasterix

Posted on • Updated on

5 React Snippets to Get You Started

As an avid code reader, I've always stashed away beautiful pieces of code that caught my eye. This has been effective habit for developing my code vocabulary.

More recently, I started using Code Notes, a free, open source app for keep track of code snippets.

Since Code Notes saves my snippets on my computer, I wasn't sure of the best way to share these. So, for now, I'm posting the snippets to this article, though I may move them elsewhere when time permits.

Initializing state without props

class App extends React.Component {
  state = {
    empty_array_state: [],
    empty_string_state: ""
  }
Enter fullscreen mode Exit fullscreen mode

Doing a (GET) fetch request

  • This should happen in componentDidMount()
  componentDidMount() {
    fetch(your_url)
    .then(res => res.json())
    .then(data => {
      this.setState({your_state:data})
    })
  }
Enter fullscreen mode Exit fullscreen mode

Handling events

  • Here you can setState based on a user's input or when any event is fired
  handleEvent = (event) => {
   ....add code here....
  }
Enter fullscreen mode Exit fullscreen mode

Iterating

  • You can still use loops within render()
  render(){

    let listItems = this.props.myList.map(item => {
      return(
        <Item
          id={item.id}
          name={item.name} />
    )
  })
    return (
      <div>
        {listItems}
      </div>
    );
  }
Enter fullscreen mode Exit fullscreen mode

Using absolute imports

  • This prevents your code from breaking in the event that you move your files
import { Header } from 'components/Header'
import { HeaderContainer } from 'containers/HeaderContainer'
import headerStore from 'store/headerStore'
Enter fullscreen mode Exit fullscreen mode

I came across absolute imports while reading Alligator.io, one of my favorite React resources. If you'd like to learn more about absolute imports, check it out this post

Top comments (0)