Home > Back-end >  How to change title from child component to parent component without hooks?
How to change title from child component to parent component without hooks?

Time:12-09

I have two components child and parent. And I want to change the title of the parent component from the child component. But without hooks.

So I have this:

class App extends Component {  

  render() {
    return (
      <div className="app">
        <ParentComponent/>
      </div>     
    );
  }
}

export default App;

and child component:

import React from 'react'

function ChildComponent(props) {
    return (
        <div>

            <h1>Child COmponent</h1>
            <button onClick={() => props.greetHandler('Niels')}>Greet parent</button>
        </div>
    )
}
export default ChildComponent;

and parent component:


class ParentComponent extends Component {

    constructor(props) {
        super(props);

        this.state = {
            parentName: 'parent'
        };

        this.greetParent = this.greetParent.bind(this);
    }

    greetParent(childname) {
        `${childname}`;
    }
    
    render() {
        return (
            <div>
                <h1>{this.state.parentName}</h1>
                <ChildComponent greetHandler={this.greetParent} />

            </div>
        )
    }
}
export default ParentComponent;

But nothing happens And I got the message:

./src/ParentComponent.js
  Line 19:  Expected an assignment or function call and instead saw an expression  no-unused-expressions

So my question: what I have to change that the title of parent component will change to Niels

CodePudding user response:

you should change the state in greetParent function

 greetParent(childname) {
this.setState({
  parentName: childname
})

}

  • Related