Shivam Sahil
Shivam Sahil

Reputation: 4925

Initializing state in React without constructor

I have a class component as shown below:

import React, { Component } from "react";
import Aux from "../../../hoc/Auxilary/Auxilary";
import ComponentDetails from "./SideBarLayoutDetails";
import DropDownDetails from "../UI/DropDown/DropDownDetails";
import Row from "../UI/Row/Row";
import "./Layouts.css";
import Dropdown from "../UI/DropDown/DropDown";
import Calendar from "../UI/Calendar/Calendar";

class SideBarLayout extends Component {

    state = {
        isActive: Array(DropDownDetails.length),
        isDateActive: false,
    }


    DropDownArrowHandler = (index) =>
    {

    }

    render()
    {
        const calendar = this.state.isDateActive ? <Calendar />:null;

        return <Aux>
                <div className = "SideBar-Central">
                                <Row Elems = {ComponentDetails.TopHeaders.elements} 
                                Container = {ComponentDetails.TopHeaders.container}
                                />
                                <Dropdown Elems = {DropDownDetails[0].DateFilter} 
                                Container = {DropDownDetails[0].DateFilterContainer}
                                />
                                {calendar}
                </div>
        </Aux>
    }
}

export default SideBarLayout;

I want to initialize this.state.isActive in a loop fashion like this:

const initializedvalue = DropDownDetails.map(elem => elem.active);

and then use this initializedvalue to assign to this.state.isActive.

But I want to do this just when the component renders in the screen. What is the best way to do so? Should I use constructor? I don't prefer it as I get a warning using super(props). Please let me know the best way to do so. My end goal is to have a this.state.isActive array ready to be used in making the decisions about rendering the screen components.

Upvotes: 0

Views: 100

Answers (1)

Soumya Ranjan Nayak
Soumya Ranjan Nayak

Reputation: 21

First, forEach does not return any value as it is a void function. So try map function instead. This will return elements for which active is true (assuming active is a boolean type property in elem)

const initializedvalues = DropDownDetails.map(elem => elem.active);

Next, if you want to use this to set this.state.isActive after render, run it in componentDidMount(). Its a lifecycle function that runs after the initial render is done.

Upvotes: 2

Related Questions