Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React state in parent or child components

I'm making a typeahead input using React and I'd like some input on where to place my state. I'm only using React, and not some architecture like Redux or what have you My root component looks like this:

import React, { Component } from 'react';
import InputSearch from './input_search';
import SearchHints from './search_hints';

class Main extends Component {
  constructor(props) {
    super(props)
    this.state =   
       /* Some state here? */
    }
  }

  render() {
    return (
      <InputSearch />
      <SearchHints />
    );
  }
}

The InputSearch obviously takes care of the <input /> markup and SearchHints takes care of rendering a list of suggestions as the user types

My question is whether or not I should keep my state in the root component, or place it in the different child components The state will contain logic for matching the user input to some data array of search suggestions, and also logic for updating the value from the a selected search hint into the input field. I feel like the logic between the two child components is kind of intermingled, which I why im unsure of where to place it.

like image 214
frisk0 Avatar asked Mar 09 '23 09:03

frisk0


1 Answers

You should always maintain your state in your root component because flow of your app revolves around your root component.So you should plan your components accordingly.

In case you feel that maintaining state of your app in root is difficult and your sub components also need to maintain some local state then you should use stores(flux,redux).

Now looking at your problem statement keeping your state at root will be a simple solution as you can just pass your state to child components and do any computations you want to do in child components.Maintaining different states for each child component will make your code more complex.

To achieve this just set your state like something

{input:""}

in your inputsearch component you can do

function:method(event)
{

this.props.setInput(event)


}
<input type="text" onChange={this.setInput}/>

In your main root component

function:setInputAsState(input)
{
this.setState({


input:input
])

}
<inputsearch  setInput={this.setInputAsState}/>
<SearchHints state={this.state.input}/>

Now compute anything you want in SearchHints component. Hope you got an idea

like image 90
Vikram Saini Avatar answered Mar 16 '23 19:03

Vikram Saini