Ooto
Ooto

Reputation: 1257

React: How to pass data to children

I am a beginner in React and what I am doing might not make sense.
What I am trying to do is just to pass a data to from a parent component which is used in every screen to children.

My code is like this.

AppDrawer.tsx

const AppDrawer: React: FC<Props> = ({
    children,
  }) => {
    const [aString, setString] = React.useState<string>('Hello');
...

<div>
  <Drawer>
    ...
  </Drawer/>
  <main>
    <div>
      <Container>
        {children}
      </Container>
    </div>
  </main>
</div>

App.tsx

<Swith>
    <AppDrawer>
        <Route path="/" component={ChildCompoent} />
        ...
        ...
    </AppDrawer>
</Switch>

ChildComponent.tsx

export default class ChildComponent extends React.Component<Props, State> {
  state = {
    ..
  }
}

And now I want to access aString in AppDrawer.tsx in child components but I couldn't figure out how I can do it. How can I do it?

Upvotes: 2

Views: 5669

Answers (3)

hungdoansy
hungdoansy

Reputation: 486

I think you can use Context here. Context allows you to pass down something from the parent component, and you can get it at the child component (no matter how deep it is) if you'd like.

I made an example link

You can read more about it here

Updated: I notice you use Route, Router, and I don't use in my codesandbox. However, it's fine though. The main idea is to use context :D

Upvotes: 2

datnv
datnv

Reputation: 35

Use render in component Route

<Route
  path='/'
  render={(props) => (
    <ChildCompoent {...props}/>
  )}
/>

And should not props aString in component AppDrawer

Upvotes: 1

Ran Marciano
Ran Marciano

Reputation: 1531

I'm not sure about the version of react and if it is still supported but this how I did this in my app. try checking for React. Children over here: https://reactjs.org/docs/react-api.html#reactchildren see if it's suitable for your case.

    render() {
        const children = React.Children.map(this.props.children, child => {
            return React.cloneElement(child, {
                ...child.props,
                setHasChangesBeenMade: (nextValue) => this.setState({ hasChangesBeenMade: nextValue })
            });
        });

        return (children[0]);
    }

for you it should be something like this :

const AppDrawer: React: FC<Props> = ({
    children,
  }) => {
    const [aString, setString] = React.useState<string>('Hello');
...

        const childrens = React.Children.map(children, child => {
            return React.cloneElement(child, {
                ...child.props,
                aString: aString
            });
        });
<div>
  <Drawer>
    ...
  </Drawer/>
  <main>
    <div>
      <Container>
        {childrens[0]}
      </Container>
    </div>
  </main>
</div>

Upvotes: 0

Related Questions