skip to Main Content

there is a component duplicated many times in another component. There is a button in this component. How do I change the style of the first component when clicking on it


<div>
<Checkbox />
<Checkbox />
<Checkbox />
<Checkbox />
<Checkbox />
<Checkbox />
</div>

2

Answers


  1. You can pass the optional props "style" from the parent component.
    for example:

    <div>
     <Checkbox style={{
       color: "blue"
      }} />
     <Checkbox />
     <Checkbox />
     <Checkbox />
     <Checkbox />
     <Checkbox />
    </div>
    

    and that’s how you can handle this in your Checkbox component –

    const Checkbox = ({
     style = {}
    }) => {
      return (
        <View style={[styles.container, ...style]} ></View> 
      )
    }
    
    Login or Signup to reply.
  2. You’ll require state somewhere but depending on what component controls it will depend on where it goes. Ashish has hinted at one solution (controlling the state from the parent) but probably the easiest method is to have the <Checkbox /> component control it instead.

    In this example I have an optional styleCanChange prop (defaults to false) that tells the component whether or not to use the blue style or not. I’ve added labels for completeness.

    const { useState } = React;
    
    function Example() {
      return (
        <main>
          <Checkbox label="One" styleCanChange />
          <Checkbox label="Two" />
          <Checkbox label="Three" />
          <Checkbox label="Four" />
        </main>
      );
    }
    
    // Default `styleCanChange` to false
    function Checkbox({ label, styleCanChange = false }) {
      
      // Set state of the checkbox
      const [checked, setChecked] = useState(false);
      
      // Set the state when the box is checked
      function handleChange() {
        setChecked(prev => !prev);
      }
      
      // Create a class depending on whether the box is
      // checked and styleCanChange is true
      const cn = checked && styleCanChange ? 'blue' : '';
      
      return (
        <div className={cn}>
          <input
            id={label}
            type="checkbox"
            onChange={handleChange}
            checked={checked}
          />
          <label htmlFor={label}>{label}</label>
        </div>
      );
    }
    
    const node = document.getElementById('root');
    const root = ReactDOM.createRoot(node);
    root.render(<Example />);
    .blue { background-color: lightblue; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.min.js"></script>
    <div id="root"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search