Mir Stephen
Mir Stephen

Reputation: 1927

Problem with passing props to child component

I have ProductList component

import Title from "./Title";

class ProductList extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    return <Title name="Our" title="Products" />;
  }
}

and Title component which is exported and then used inside ProductList component.

class Title extends Component {
  constructor(title, name) {
    super();
    this.title = title;
    this.name = name;
  }
  render() {
    return (
      <div className="product-title">
        {this.name} <strong>{this.title}</strong>
      </div>
    );
  }
}

But I'm not able to render title and name.

Moreover, one additional question If i write that class based component to function based component we need to do it this way function Title({ name, title }) why do we need parenthesis {} to wrap name and title there?

Upvotes: 1

Views: 60

Answers (1)

Dupocas
Dupocas

Reputation: 21357

props are available inside this.props for class based components. You don't need a constructor here

class Title extends Component {
  render() {
    const {name, title } = this.props
    return (
      <div className="product-title">
        {name} <strong>{title}</strong>
      </div>
    );
  }
}

If i write that class based component to function based component we need to do it this way function Title({ name, title }) why do we need brackets to wrap name and title there?

This is a pattern called destructuring assignment which makes it possible to unpack values from arrays, or properties from objects, into distinct variables

You can pass an object as parameter and only destructure it inside the function's body, or directly in the declaration

const user = {name: 'John', surname: 'Doe'}
logUser(user)

const logUser = user =>{
   const { name, surname } = user

   console.log(name, surname)
}

Is the equivalent of

const logUser = ({ name, surname }) => console.log(name, user)

Since the only argument received by a functional component is props you can pass it like

<Child foo='bar' />

And directly destructure the argument from props object

const Child = ({ foo }) => <span> {foo} </span>

Upvotes: 5

Related Questions