React file structure snippets to get you started

Jasterix - Jul 2 '19 - - Dev Community

React and I haven't been the best of friends recently. Passing data between components and working from component to subcomponents, each with different states isn't hasn't been as intuitive for me.

So today, I decided to make the time to find some helpful patterns for structuring your React files.

Components that will probably hold state

  • Forms
  • Inputs
  • Conditional display

General Form.js

    state ={
        title: "",
        description: ""
    }

    handleChange = (event) => {
        this.setState({title: event.target.value})
    }
    handleSubmit = (event) => {
        this.props.newBook(this.state)
    }

...

return (
    <form onSubmit={this.handleSubmit}>
    <input onChange={this.handleChange} value= {this.state.title}>
Enter fullscreen mode Exit fullscreen mode

General App.js

    state = {
        books: [] 
    }

    ComponentDidMount() {
        fetch(url)
        .then(res => res.json())
        .then(data => {
            this.setState({books: data})
    }

    handleNewBook = (bookData) => {
        const newBook = { ...bookData }
        this.setState({books:[...this.state.books, newBook]})
}

render() {
    return(
        <NewBookForm onNewBook = {this.handleNewBook} />
        <Container books= {this.state.books} />
Enter fullscreen mode Exit fullscreen mode

General Container.js

render() {
    const books = this.props.books.map(bookData => <Book book={bookData} />)
return (
    <div>
    { books }
    </div>
)
Enter fullscreen mode Exit fullscreen mode

General Book.js

    <div>
        <h1> {this.props.book.title} </h1>
        <p> {this.props.book.content} </p>
    </div>
Enter fullscreen mode Exit fullscreen mode
  • Check out this article for a more in-depth look at creating and using React components
  • I also recommend this article, which offers a deep dive into passing props between components (although it does use this.state, which I believe makes React more difficult)
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player