G
G
georgedubinsky88882019-12-02 11:55:03
JavaScript
georgedubinsky8888, 2019-12-02 11:55:03

Questions about one line of React code?

Hello. I'm learning JS and React, and I want to understand one line of code that I don't really understand.
There is a code that implements tabs:

const items = [
  {content: 'London'},
  {content: 'Paris' } 
];

class Content extends React.Component {
  render() {
    return (
      <div className="content">
        <p>{this.props.content}</p> 
      </div>
    );
  }
}

class Tabs extends React.Component {
  state = {
    active: 0,
  }

  open = (e) => {
     this.setState({
        active: +e.target.dataset.index,
     });
  }
  
  render() {
    return (
      <div>
        
        <div className="tab">
        
          {this.props.items.map((n, i) => (
            <button onClick={this.open} data-index={i}>{n.content}</button>
          ))}
        </div>

        {this.props.items[this.state.active] && <Content {...this.props.items[this.state.active]} />}

      </div>
    );
  }
}

ReactDOM.render(<Tabs items={items} />, document.getElementById('root'));

And I have questions about this line:
{this.props.items[this.state.active] && <Content {...this.props.items[this.state.active]} />}

1) Why do &&we write before the operator not just this.state.activea this.props.items[this.state.active]? What is it for? 2) Why is it not written simply
after the operator . Why repeat what is written on the left of the operator ? So why is the code written this way? &&<Content atr={this.props.items} />&&

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
McBernar, 2019-12-02
@georgedubinsky8888

1. This is the element number of the items array. In active, the tab number is written, as I understand it.
2. Props of the active tab are passed to the content. See point 1. It is obvious that all props do not need to be transferred there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question