reactjs
reactjs

Reputation: 13

React: How can I acces to props of a functional component in a class component

// React is loaded and is available as React and ReactDOM
// imports should NOT be used
const TodoItem = (props) => <li onClick={props.onClick}>{props.item.text}</li>

class TodoList extends React.Component {
  render() {
    const { items, onListClick } = this.props;
    return (<ul onClick={onListClick}>
      {items.map((item, index) => 
                 <TodoItem item={item} key={index} onClick={this.handleItemClick.bind(this, item)}/>)}
    </ul>);
  }
  
  handleItemClick(item, event) {
    // Write your code here
    if(item.done == true) {
      event.stopPropagation();
    } else {
      this.props.onItemClick(item, event);
    }
  }
}


const items = [ { text: 'Buy grocery', done: true },
  { text: 'Play guitar', done: false },
  { text: 'Romantic dinner', done: false }
];

const App = (props) => <TodoList
  items={props.items}
  onListClick={(event) => console.log("List clicked!")}
  onItemClick={(item, event) => { console.log(item, event) }}
/>;

document.body.innerHTML = "<div id='root'></div>";
const rootElement = document.getElementById("root");
ReactDOM.render(<App items={items}/>, rootElement);

In the functional App component I assign the property onItemClick to the ToDoList component which is a class component.

In the class component ToDoList I acces to the property with

this.props.onItemClick(item, event); 

How is it possible to pass props from a functional component to a class component or from class component to functional component

and why can I use this to acces a prop of a functional component when the this doesn't work in functional components?

Upvotes: 0

Views: 661

Answers (1)

heyitsvajid
heyitsvajid

Reputation: 1121

Whenever we try to access props or state using class components we need to use the “this” keyword. However, it is not necessary to use the “this” keyword for functional components.

Inside a functional component, we are passing props as an argument of the function. In this case, you have to use props.name instead of this.props.name.

const FunctionalComponent = (props) => {
 return <h1>Hello, {props.name}</h1>;
};

Below is example of class. Since it is a class, you need to use this to refer to props.

class ClassComponent extends React.Component {
  render() {
    const { name } = this.props;
    return <h1>Hello, { name }</h1>;
 }
}

Upvotes: 2

Related Questions