Reputation: 77
I've been attempting to create a react app similar to monkeytype; where letters are formatted as the user types them. I've created a word functional component that wraps tags, but I'm running into trouble now as I try and dynamically format a bunch of these word components depending on user input. One idea I have is to store these Word components in an array then use array indexing to call a method on the Word components that needs to be updated, but I've never experienced with react component objects or understand how the object methods work. (From what I observe, you can't call methods on react components?) Here's an example of what it looks like, how can I, say, at run-time allow the user to navigate to the "Current" word and style that word conditionally?
import Word from './word';
import './typeTest.css'
export default function TypeTest() {
const test1 = "the quick brown fox jumped over a tree and tripped over that tree the quick brown fox jumped over a tree and tripped over that tree the quick brown fox jumped over a tree and tripped over that tree the quick brown fox jumped over a tree and tripped over that tree";
const test1Arr = test1.split(' ');
return (
<div className='outer-word-container'>
<div className="word-container">
{test1Arr.map(monoWord => <Word inputWord = {monoWord}/>)}
<Word inputWord="Scoll"/>
</div>
</div>
)
}
Any help would be appreaciated!
Upvotes: 1
Views: 5167
Reputation: 2119
As your question asked, I tried to have a sample of making dynamic style
which depends, in my case, on the index of the array. Changing colors of the background made me come up with this solution:
App.js
import { Word } from "./word";
//import './typeTest.css'
export default function App() {
const test1 =
"the quick brown fox jumped over a tree and tripped over that tree the quick brown fox jumped over a tree and tripped over that tree the quick brown fox jumped over a tree and tripped over that tree the quick brown fox jumped over a tree and tripped over that tree";
const test1Arr = test1.split(" ");
return (
<div>
<div style={{display:"flex"}}>
{test1Arr.map((monoWord, index) => (
<Word
inputWord={monoWord}
style={{
background: `#${(index*2).toString(16)}${index.toString(16)}${((index+1)/2).toString(16)}`
}}
/>
))}
<Word inputWord="Scoll" />
</div>
</div>
);
}
word.js
export const Word = (props) => {
return <h1 style={props.style}>{props.inputWord}</h1>;
};
As you can see in the word.js
component we get the props of style, which is applied later to the child component. Passing the background is the most visible change in styles, so I implemented that. The same technique you would use if you implement a className
, which is conditionally writable as string. Here is the example in sandbox.
Upvotes: 2