Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Passing components as children in react

const UserCard = ({ name, children }) => {
  return (
    <div>
      <p>Name: {name}</p>
      {children}
    </div>
  )
}

const UserIcon = ({ profilePic }) => {
  return <img src={profilePic} alt="profile" />
}

function App() {
  return (
    <div>
      <UserCard name="Ranjeet">
        <UserIcon profilePic="image.jpg" />
      </UserCard>
    </div>
  )
}

export default App
Comment

react pass props to children

import React, { Children, isValidElement, cloneElement } from 'react';

const Child = ({ doSomething, value }) => (
  <div onClick={() => doSomething(value)}>Click Me</div>
);

function Parent({ children }) {
  function doSomething(value) {
    console.log('doSomething called by child with value:', value);
  }

  render() {
    const childrenWithProps = Children.map(children, child => {
      // Checking isValidElement is the safe way and avoids a TS error too.
      if (isValidElement(child)) {
        return cloneElement(child, { doSomething })
      }

      return child;
    });

    return <div>{childrenWithProps}</div>
  }
};

ReactDOM.render(
  <Parent>
    <Child value="1" />
    <Child value="2" />
  </Parent>,
  document.getElementById('container')
);
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript tostring method 
Javascript :: js remove first element from array 
Javascript :: run onclick function once 
Javascript :: how to download file from link in react 
Javascript :: .NET number values such as positive and negative infinity cannot be written as valid JSON. 
Javascript :: != vs !== javascript 
Javascript :: Iterate object using ngFor in angular 
Javascript :: js is undefined or null 
Javascript :: nodejs for windows 7 
Javascript :: vue get if checkbox is checked 
Javascript :: js get file location 
Javascript :: mongodb replace string regex 
Javascript :: vscode rest api extention POST method 
Javascript :: hide a div in jquery 
Javascript :: circular progress for react 
Javascript :: file name in react input 
Javascript :: angular redirect to external url 
Javascript :: node js run for loop asynchronously 
Javascript :: how to add checked in javascript 
Javascript :: javascript Sum of a sequence 
Javascript :: create url with query parameters javascript 
Javascript :: Iteration over JS object 
Javascript :: electron new window 
Javascript :: how to remove child element in jquery 
Javascript :: base64 to image nodejs 
Javascript :: random positive or negative javascript 
Javascript :: run a local instance of Kibana on docker and connect to elasticsearch 
Javascript :: swap two variables javascript 
Javascript :: vuetify autocomplete get input value 
Javascript :: discord.js 
ADD CONTENT
Topic
Content
Source link
Name
1+8 =