반응형

삼항연사자를 이용해서 style값 변경하기

import { useState } from 'react';

const App = () => {
    const [test, setTest] = useState('');
    
    const onChange = (option) => {
        if (option === '1') setTest('1');
        else setTest('2');
    };
    
    return (
        <div>
            <div onClick={() => onChange('1')} style={{background: test === '1' ? 'blue' : ''}}>test1</div>
            <div onClick={() => onChange('2')} style={{background: test === '2' ? 'orange' : ''}}>test2</div>
        </div>
    );
}

export default App;

 

삼항연사자를 이용해서 className값 변경하기

import { useState } from 'react';

const App = () => {
    const [test, setTest] = useState('');
    
    const onChange = (option) => {
        if (option === '1') setTest('1');
        else setTest('2');
    };
    
    return (
        <div>
            <div onClick={() => onChange('1')} className={test === '1' ? 'adc' : ''}}>test1</div>
            <div onClick={() => onChange('2')} className={test === '2' ? 'def' : ''}}>test2</div>
        </div>
    );
}

export default App;

 

반응형

+ Recent posts