D.R D.R - 21 days ago 4
React JSX Question

How can I make each child of component has a state? react redux

In my project, there are HomeIndexView and table component. So, when a user logs in to his account, in HomeIndexView, it shows all tables in the database. What I want to do is that make each table have a state so that it changes color of depends on its state(depends on child's state)... How can I do this??

My table component has a state like below...

const initialState = {
allTables: [],
showForm: false,
fetching: true,
formErrors: null,
};


Thanks in advacne

EDIT ---1

HomeIndexView

class HomeIndexView extends React.Component {
componentDidMount() {
setDocumentTitle('Table_show');
}

componentWillunmount() {
this.props.dispatch(Actions.reset());
}

_renderAllTables() {
const { fetching } = this.props;

let content = false;


if(!fetching) {
content = (
<div className="tables-wrapper">
{::this._renderTables(this.props.tables.allTables)}
</div>
);
}


return (
<section>
<header className="view-header">
<h3>All Tables</h3>
</header>
{content}
</section>
);
}


_renderTables(tables) {
return tables.map((table) => {
return <Table
key={table.id}
dispatch={this.props.dispatch}
{...table} />;
});

}

render() {
return (
<div className="view-container tables index">
{::this._renderAllTables()}
</div>
);
}

}


EDIT--2

_handleClick () {

const { dispatch } = this.props;

const data = {
table_id: this.props.id,

};

if (this.props.current_order == null) {

dispatch(Actions.create(data));

Object.assign({}, this.state, {
tableBusy: true
});

}

else{

this.props.dispatch(push(`/orders/${this.props.current_order}`));
}


}

Answer

The state you shared above is part of the global state (where tableReducer use) not the table's component state, so what you need is to initialize component state in Table React component, so that you can check some values to render css differently something like this:

import React from "react";

class TableComponent extends React.Component {

  componentWillMount() {
    this.setInitialState();
  }

  setInitialState() {
    this.setState({ isWhatever: false });
  }

  render() {
    return (
      <div>
        <h1 classname={this.state.isWhatever ? 'css-class' : 'another-class'}>
            {this.props.id}
        </h1>
      </div>
    );
  }
}