I made vigenere cipher in react. everything works perfectly regarding vigenere cipher algorithm. there is just one thing i want to add. when i take one letter from text and one letter from password, i want correspongind row and column on the board to be colored one by one. for example: if password is cat and text is rat, first i want to light up coresponding row and column of c and r, than on the next step a and a, then t and t. thats it.
currently i have no idea how to use useState()
in such a way to get every column and row colored on each step. i managed to color last row and column checked but thats not what i am looking for.
// import { useState } from 'react';
// import './App.css';
function VigenereCipher() {
const georgianLetters = 'აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰ';
const table = Array.from({ length: 33 }, (_, i) =>
Array.from({ length: 33 }, (_, j) => georgianLetters[(i + j) % 33])
);
const [password, setPassword] = React.useState('');
const [text, setText] = React.useState('');
const [ciphered, setCiphered] = React.useState('');
const [row, setRow] = React.useState(null);
const [col, setCol] = React.useState(null);
const handlePasswordChange = (event) => {
setPassword(event.target.value);
};
const handleTextChange = (event) => {
setText(event.target.value);
};
const handleCipherButtonClick = () => {
if (!password || !text) {
setCiphered('');
alert(`შეავსეთ პაროლის და ტექსტის ველები`);
return;
}
let k = 0;
let cipheredText = '';
for (let i = 0; i < text.length; i++) {
if (text[i] === ' ') {
cipheredText += ' ';
} else {
const rowIndex = georgianLetters.indexOf(text[i]);
const colIndex = georgianLetters.indexOf(password[k]);
if (rowIndex !== -1 && colIndex !== -1) {
cipheredText += table[rowIndex][colIndex];
k = (k + 1) % password.length;
}
}
}
setCiphered(cipheredText);
};
return (
<div className="main">
<table>
<tbody>
{georgianLetters.split('').map((letter, i) => (
<tr key={i} style={i === row ? {backgroundColor: 'red'}: {}}>{georgianLetters.split('').map((innerLetter, j) => (
<td
key={j}
style={{
backgroundColor: i === row && j === col ? 'purple': j === col ? 'red': 'none',
}}
>{table[i][j]}</td>
))}
</tr>
))}
</tbody>
</table>
<div className="right-side">
<div className='pass-text'>
<label>პაროლი</label>
<input type="text" value={password} onChange={handlePasswordChange} />
<label>ტექსტი</label>
<textarea value={text} onChange={handleTextChange}></textarea>
</div>
<button onClick={handleCipherButtonClick}>დაშიფვრა</button>
<div className="ciphered">
<textarea readOnly value={ciphered}></textarea>
</div>
</div>
</div>
);
}
ReactDOM.render(<VigenereCipher/>, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<div id="root"></div>