Search code examples
reactjsgraphqlapollo-client

Passing variable to react component


I have:

        function Button(){
        /*.. useQuery ...*/
         const onClick = props => (
         console.log(props.target.value)
           )
        return(
          /*  ... */
            <button value={id} onClick={onClick} >details</button>
        )
        }
I want to pass props.target.value to class react.component. where it will be used to display popup. I want something like:
class Details extends React.Component{
/* if thereIsID == 0 then "" or if thereIsID == not 0 then show popup with data according to props.target.value */
}
I used many different variants.. Maybe I am trying not right approach? Can you recommend something?

Solution

  • import React, { useState } from 'react';
    import './style.css';
    
    function Button({ onClickHandler }) {
      /*.. useQuery ...*/
      const onClick = (props) => {
        onClickHandler(props.target.value);
      };
      return (
        /*  ... */
        <button value={1} onClick={onClick}>
          details
        </button>
      );
    }
    
    class Details extends React.Component {
      /* if thereIsID == 0 then "" or if thereIsID == not 0 then show popup with data according to props.target.value */
    
      render() {
        return (
          <div>
            Details of Details : {this.props.detail === 0 ? '00000' : 'not 0000000'}
          </div>
        );
      }
    }
    
    export default function App() {
      const [show, setShow] = useState(false);
      const [detail, setDetail] = useState('');
    
      const onClickHandler = (val) => {
        setDetail(val);
        setShow((prev) => !prev);
      };
    
      return (
        <div>
          <Button onClickHandler={onClickHandler} />
          {show && <Details detail={detail} />}
        </div>
      );
    }

    Link to test : https://react-sjsxn2.stackblitz.io