skip to Main Content

I would like to create a button component that uses html as below.

<button class="button_57" role="button">
   <span class="text">Button</span>
   <span>Alternate text</span>
</button>

I want to be able to use one Button component created with react.

<CustomButton {...otherProps}>{children}</CustomButton>

Is there a way to modify the span contents within Button component with props like so?

<Button span_content1={''} span_content2={''}></Button>

I’ve only found passing spans as children to work.

<Button>
   <span class='text'>Button</span>
   <span>Alternate text</span>
</Button>

2

Answers


  1. When using React we could create a component like this

    function ButtonName({ content1, content2}) {
       return(
          <Button>
             <span class='text'>{content1}</span>
             <span>{content2}</span>
          </Button>
       )
    }
    

    After creating the component we can call the Component Name like this.

    <ButtonName content1="Button" content2="Alternate text" />

    To change the content, we can replace the content1 and the content2 with other values

    Login or Signup to reply.
  2. import styled from 'styled-components';
    
    // Define your styled component
    const CustomButton = styled.button`
      // Add your styles here
    `;
    
    const Button = ({ span_content1, span_content2, ...props }) => (
      <CustomButton {...props}>
        <span>{span_content1}</span>
        <span>{span_content2}</span>
      </CustomButton>
    );
    
    // Use your component
    <Button span_content1="Button" span_content2="Alternate text" />

    Button component that accepts span_content1 and span_content2 as props and uses them as the content for the two span elements. The rest of the props (…props) are forwarded to the CustomButton component.

    https://react.dev/learn/passing-props-to-a-component

    https://styled-components.com/docs/basics#adapting-based-on-props

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search