Search code examples
javascriptreactjsstatereact-props

React - State from class to hook


i don't understand something.

From my parents class, i give state to my children class like this :

<TrainingArea
   getHtmlGrain={() => this.getHtmlGrain()}
   right={this.state.right}
   grain_language={this.state.lang}
   id_grain={this.state.grain[this.state.currentGrain]}
   skinPath={this.state.training.skin_path}
   selectedBlock={this.state.selectedBlock}
 />

and before to take the 'props' in the children class i use this this :

this.props.skinPath

but now, i don't understand how i can take this props in a 'hook class react'. Or is not possible? my parent class look like this :

import TrainingArea from '../Blocks/General/TrainingArea'

class BlockPage extends Component {

state = {
//some state
}

 render() {
   return (
      <TrainingArea
       getHtmlGrain={() => this.getHtmlGrain()}
       right={this.state.right}
       grain_language={this.state.lang}
       id_grain={this.state.grain[this.state.currentGrain]}
       skinPath={this.state.training.skin_path}
       selectedBlock={this.state.selectedBlock}
     />
   )}

How I'm using it in my child class :

const TrainingArea = (props) => {
    console.log(props.skinPath)
    return (
       <h1>hi</h1>
    )
}

useEffect(()=> {
    TrainingArea()
})

Can someone help me? thx a lot


Solution

  • You basically go from this:

    class MyComponent extends React.Component {
        render() {
            const prop = this.props.prop;
            const someState = this.state.someState;
            // ...
            return <button onClick={() => this.setState({ someState: 'state' })}>Example</button>;
        };
    }
    

    to this:

    function MyComponent(props) {
        const prop = props.prop;
        const [someState, setSomeState] = React.useState();
        // ...
        return <button onClick={() => setSomeState('state')}>Example</button>;
    }