Search code examples
reactjscomponentsreact-propsreact-state

How to pass value to props from component and set state


I'm new in react and try to pass a value from the parent component to the child component to the props and store the value in the state. But it doesn't even call the console.log statements

This is my function to change the string by clicking on the button

let actionToPerform = "";

function changeEdit(){
    if(actionToPerform === 'edit'){
        actionToPerform = 'new'
    }else{
        actionToPerform = 'edit'
    }
}

In the parent component, in render I have this:

<Edit action={actionToPerform}
                    />

Child component

import React from 'react'; import * as styles from './edit.module.css';

export default class Edit extends React.Component {

    constructor(props){
        super(props);
        this.state = {actionToPerform: this.props.actionToPerform}
        console.log("props:" + props)
        console.log("parsed state: " + this.state)
    }

    showContent = ()=>{
        if(this.state.actionToPerform == "edit"){
            return <div>Shoppinliste bearbeiten</div>
        }
    }

   render() {
       return (
          this.showContent
       )
   }
}

my goal is, that based on the state which is change by clicking on the button, to show the div or not.


Solution

  • You are passing action props to the child, but parsing actionToPerform. You need to parse action in the child.

    Console log should be outside the constructor.

    export default class Edit extends React.Component {
    
    constructor(props){
        super(props);
        this.state = {actionToPerform: this.props.action}
       
    }
    
    
    
    showContent = ()=>{
        console.log("props:" + props)
        console.log("parsed state: " + this.state)
    
        if(this.state.actionToPerform == "edit"){
            return <div>Shoppinliste bearbeiten</div>
        }
    }
    
     render() {
       return (
          this.showContent
       )
      }
      }