Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-redux tutorial : Where does children come from [duplicate]

I am following the react-redux tuto : http://redux.js.org/docs/basics/ExampleTodoList.html

Looking at link.js, I am wondering where does the {children} come from

import React from 'react'
import PropTypes from 'prop-types'

const Link = ({ active, children, onClick }) => {
  if (active) {
    return {children}
  }

  return (
     {
        e.preventDefault()
        onClick()
      }}
    >
      {children}
    
  )
}

Link.propTypes = {
  active: PropTypes.bool.isRequired,
  children: PropTypes.node.isRequired,
  onClick: PropTypes.func.isRequired
}

export default Link

link.js is being used by the container component FilterLink.js. FilterLink passes both the "active" value and onclick function but no explict children is passed to link.js

import { connect } from 'react-redux'
import { setVisibilityFilter } from '../actions'
import Link from '../components/Link'

const mapStateToProps = (state, ownProps) => {
  return {
    active: ownProps.filter === state.visibilityFilter
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    onClick: () => {
      dispatch(setVisibilityFilter(ownProps.filter))
    }
  }
}

const FilterLink = connect(
  mapStateToProps,
  mapDispatchToProps
)(Link)

export default FilterLink

Please clarify.

like image 903
redochka Avatar asked Oct 27 '25 14:10

redochka


1 Answers

In React you may have two types of components. A class that extends React.Component or a functional component which is just a vanilla JavaScript function. The functional components also receives props similarly to the class where we use this.props (or receive them as first argument of the constructor. For example:

import React from 'react';

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    const { name } = this.props;

    return <p>Hello { name }</p>;
  }
}

<MyComponent name='Jon Snow' />

Or as functional component:

function MyComponent(props) {
  const { name } = props;

  return <p>Hello { name }</p>;
}

The confusion in your case comes from the fact that there is a destructing of the props directly in the function definition. So MyComponent above may be written like:

function MyComponent({ name }) {
  return <p>Hello { name }</p>;
}

The children prop in React represents what's added as child elements of the component. For example:

<MyComponent>
  <Name />
</MyComponent>

or even

<MyComponent>
  { () => <p>Hello world</p> }
</MyComponent>

<Name /> and () => <p>Hello world</p> is what props.children is equal to.

In your example children will be what's put inside FilterLink. For example:

<FilterLink>
  <VisibleOnlyIfActiveIsTruethy />
</FilterLink>
like image 87
Krasimir Avatar answered Oct 29 '25 05:10

Krasimir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!