user1176111
user1176111

Reputation: 121

Use destructuring assignment inside state

class BottomPanelProgramTabs extends React.Component<Props, State> {
  state = {
    activeTab: this.props.children[0].props.label,
  };

...

ESLint want me to use destructuring assignment on

this.props.children[0].props.label

any ideas on how to do that?

Upvotes: 0

Views: 347

Answers (2)

Junius L
Junius L

Reputation: 16132

 class BottomPanelProgramTabs extends React.Component<Props, State> {

  state = {
    activeTab: 'default label'
  };

  componentDidMount = () => {

    const [{ props: { label } }] = this.props.children;

    this.setState({
      activeTab: label || 'default label',
      ...
    })
  }

  ...

You can mix destructing by getting the first element with [] and get the props with {}.

For example:

using [child] will give us the first element in the array.

const children = [{
    props: {
      label: 'Some label'
    }
  },
  {
    props: {
      label: 'Second label'
    }
  },

  ,
  {
    props: {
      label: 'another label'
    }
  }]
  
  const [child] = children;
  
  console.log(child);

to get props we can continue mixing our destruction by adding [ {props} ] which returns props object.

const children = [{
    props: {
      label: 'Some label'
    }
  },
  {
    props: {
      label: 'Second label'
    }
  },

  ,
  {
    props: {
      label: 'another label'
    }
  }]
  
  const [ {props} ] = children;
  
  console.log(props);

to get the label from props will can do this [{ props: { label } }]

const children = [{
    props: {
      label: 'Some label'
    }
  },
  {
    props: {
      label: 'Second label'
    }
  },

  ,
  {
    props: {
      label: 'another label'
    }
  }]
  
  const [{ props: { label } }] = children;
  
  console.log(label);

With complex data

const children = [{
    props: {
      label: [{
        data: {
          title: 'complex destructor'
        }
      },
      {
        data: {
          title: 'complex destructor 2'
        }
      }]
    }
  },
  {
    props: {
      label: 'Second label'
    }
  },

  ,
  {
    props: {
      label: 'another label'
    }
  }]

 const [{ props: { label: [ { data: { title } } ] } }] = children;

console.log(title)

Upvotes: 0

sathish kumar
sathish kumar

Reputation: 1507

you can do like this. For more reference about prefer-destructuring

class BottomPanelProgramTabs extends React.Component<Props, State> {
  constructor(){
        let [props] = this.props.children;
         state = {
          activeTab : props.label
         }

   }

Upvotes: 1

Related Questions