Search code examples
javascriptreactjsstyled-components

React: How to pass width as a prop from the component


I am trying to create a component, whose width can be specified wherever the component can be used

Like:

<Button label="button" width="80%" />

const TestButton = styled.button`
  color: red;
`;

var React = require('react');

var Button = React.createClass({

render: function () {

return (
  <TestButton>{this.props.label}</TestButton>
);
}
});

module.exports = Button;

how can I achieve this?


Solution

  • If you're using styled-components you can pass the width prop to the component and set its width:

    <Button label="button" width="80%" />
    
    const TestButton = styled.button`
      color: red;
      width: ${(props) => props.width}
    `;
    
    var React = require('react');
    
    var Button = React.createClass({
    
      render: function () {
    
        return (
          <TestButton width={this.props.width}>{this.props.label}</TestButton>
         );
        }
      });
    
    module.exports = Button;