Niv
Niv

Reputation: 133

react using function on another component render

I dont know why I gets confused here but I have a simple function on one component that I want to use on another component jsx return...

how can I do that, I am not passing it as props correctly so its not working

here is my code, I want to use the handleC function

const ImageGrid = ({setSelectedImg}) => {

  const { docs } = useFirestore('images');

  const [user, setUser] = useState({});

    onAuthStateChanged(auth, (currentUser) => {
     setUser(currentUser);
    })

  const handleC = () => {
    console.log("HELLO")
  }

return (
......
)

on this component called Myimage

const Myimage = ({selectedImg, setSelectedImg, handleC}) => {

    const handleclick = (e) => {
        if (e.target.classList.contains('backdrop')){
            setSelectedImg(null);
        }
    }

  return (
    <motion.div className='backdrop' onClick={handleclick}
    initial={{opacity: 0}}
    animate={{opacity: 1}}>
        <FcRemoveImage onClick={handleC} style={{
            fontSize: '50px',
            cursor: 'pointer'
        }}/>
        <motion.img src={selectedImg} alt="full sized picture" initial={{y: "-100vh" }} animate={{y: 0}}/>
    </motion.div>
  )
};

Upvotes: 0

Views: 284

Answers (1)

Josh Lin
Josh Lin

Reputation: 2437

// Example stateless functional component
const SFC = props => (
  <div onClick={props.handleC}>click me</div>
);

// Example class component
class Thingy extends React.Component {
  render() {
    return (
      <div>
        <SFC handleC={()=>alert('hello')} />
      </div>
    );
  }
}

// Render it
ReactDOM.render(
  <Thingy />,
  document.body
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Upvotes: 1

Related Questions