vehk
vehk

Reputation: 107

React Component code organization best practise

Is it ok to have all the functions inside of the App.js in React and then passing them to the other components through context:

export default class App extends Component {
constructor(props) {
    super(props);

    this.state = {
        listName: '',
        existingListNames: [],

        item: {
            id: '',
            toDo: ''
        },
        listItems: []
    };

    this.onItemChange = this.onItemChange.bind(this);
    this.onItemAdd = this.onItemAdd.bind(this);
}

componentDidMount() {
    axios.get('http://localhost:8080/v1/names')
        .then(response => {
            const listItems = response.data;
            listItems.forEach(item => {
                this.setState({
                    existingListNames: [...this.state.existingListNames, item.name]
                })
            })
        })
}



onItemChange(event) {
    this.setState({
        item: {
            id: uuid(),
            [event.target.name]: event.target.value
        }
    });
}

onItemAdd(event) {
    event.preventDefault();

    const { item } = this.state;
    this.setState({
        listItems: [...this.state.listItems, item],
        item: {
            id: '',
            toDo: ''
        }
    });

    document.getElementById('formItem').reset();
}



render() {
    const currentItem = this.onItemChange;
    const addItem = this.onItemAdd;
    const { listItems, existingListNames, listName } = this.state;

    return (
        <div className="main-container">
            <Context.Provider
                value={{
                    currentItem,
                    addItem,
                    removeItem,
                    listItems,
                    existingListNames,
                    listName
                }}
            >
                <InputContainer />
            </Context.Provider>
        </div>
    );
}
}

And then access them from the component:

import React, { useContext } from "react";
import Context from "../../../context/Context";

export default function ItemInput() {
    const { currentItem, addItem } = useContext(Context);

    return (
        <form className="item" id="formItem">
            <input
                onChange={currentItem}
                type="text"
                className="newInput"
                name="toDo"
                placeholder="New Task"
                autoComplete="off"
            />
            <button onClick={addItem} className="checkButton">
                <i className="fas fa-check fa-sm"></i>
            </button>
        </form>
    );
}

Or is it better to separate them into different files and import straigth into components instead. What if App.js gets really big with lots of functions?

Upvotes: 1

Views: 149

Answers (1)

Tobiah Rex
Tobiah Rex

Reputation: 2357

I'm going to assume you're looking for the "best practice" answer, since that's what you put in your title. That answer depends on your use case:

Propagating handlers to their respective children, should be done at the nearest parent to the child component. The only reason to use context would be if the parent-child relationship is not applicable to your Component hierarchy; i.e. one component to a random-component-nowhere-near-the-other.

Beyond one of those 2 scenarios, there's a lot of debate around the React community on using Context or Props for direct descendent children. To prepare yourself well for the eventual debate, feel free to read up on the pros & cons of each . If you do opt for context tho, there's some definite disadvantages.

Upvotes: 1

Related Questions