0

I am having difficulties understanding how to build a rather simple component that has a variety of props that need to be accessed inside a nested component, within. I don't even know if that is how to correctly explain my situation, regardless I feel like this should be simple.

I'll explain. I have a component as follows:

<Widget
  layout="small"
  header="This is the header"
  icon={<UploadIcon/>}
  title="This is the title"
  caption="This is the caption to a widget it should have a character count"
  to="/tosomwhere"
  href="http://www.website.com"
  link="Link Title"
/>

And the component code.

const Widget = (props) => {
  return (
    <WidgetWrapper layout={props.layout}>
      hello world
      {props.title}
    </WidgetWrapper>
  );
}

Widget.propTypes = {
  layout: PropTypes.oneOf(['small', 'large', 'dual']),
  header: PropTypes.string,
  icon: PropTypes.element,
  title: PropTypes.string,
  caption: PropTypes.string,
  to: PropTypes.string,
  href: PropTypes.string,
  link: PropTypes.string,
};

Widget.defaultProps = {
  layout: 'small'
};

export default Widget;

As you can see I am including a component inside the component. It's purpose is purely visual (size of widget, color, ext), but it needs to wrap all the props coming from

I can access props.layout as it's outside the component, but I can't access props.title inside that belongs to .

How is this done? Do I need to pass props down through so I can access them that way? I tried to add a props={props} to with no success...

1
  • 1
    If you want to forward all the props to WidgetWrapper, you can use <WidgetWrapper {...props} /> Commented Jan 4, 2019 at 14:13

3 Answers 3

3

I don't think you should include props like that inside a tag. The way I use to write my React is just pass the props inside the tag like you did with props.layout, and then make use of these props inside the code of your WidgetWrapper.

Instead of writing every single prop in the tag, you could just use the spreading operator:

<WidgetWrapper {...props}/>
Sign up to request clarification or add additional context in comments.

Comments

0

I am not sure if I fully understand your problem. Do you want to access some props in Widget component from WidgetWrapper? in this case I think you should pass what you need down. Or do you have many props that you want to pass down to the wrapper?

Comments

0
const RenderApp = props => {
  return (
    <div>
      hello {props.title}
    </div>
  );
}



class App extends React.Component {
  render(){
    return (      
        <RenderApp title="world"/>      
    );
  }
}

This works for me and prints "hello world"... Maybe I'm missing the point...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.