DEV Community

Jasterix
Jasterix

Posted on • Edited on

5 2

React file structure snippets to get you started

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)

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs