I have a functional component:
function Tile(props: any) {
const selectTile = (() => {
...
})
return (
<div>
...
</div>
)
}
I then create another functional component which will hold many tiles.
function Grid(props: any) {
const selectAllTiles = (() => {
})
return (
<div>
<Tile></Tile>
<Tile></Tile>
<Tile></Tile>
</div>
)
}
My question is, how can I call the selectTile() function for each Tile within the selectAllTiles() function? What approaches are there?
I would make the parent component keep track of selected tiles, and it will then inform each Tile (through props) if it is selected or not.
If a Tile should be able to "make itself selected", then a function can be passed from the parent into each Tile (also through props) that the Tile can call and which will update the selected tiles collection in the parent.
Updated code:
function Tile(props: any) {
const { isSelected, makeSelected } = props;
return (
<div style={{ ... something based on isSelected ... }}>
<button type="button" onClick={makeSelected}>Select me</button>
</div>
)
}
function Grid(props: any) {
const [isSelected, setIsSelected] = useState<bool[]>([false, false, false]);
const makeSelected = (index: int) => {
// ...
setIsSelected(...);
}
return (
<div>
<Tile isSelected={isSelected[0]} makeSelected={() => makeSelected(0)}></Tile>
<Tile isSelected={isSelected[1]} makeSelected={() => makeSelected(1)}></Tile>
<Tile isSelected={isSelected[2]} makeSelected={() => makeSelected(2)}></Tile>
</div>
)
}
This is just an (untested) example, many approaches are possible.
why don't use like this:
function Tile(props: any) {
return (
<div>
...
</div>
)
}
const selectTile = (() => {
...
})
Related
I have referred other questions asked here by OPs but none seems to work for me. I have one layout and in that layout there is one toolbar which I am using to submit forms. Now to make that happen I using one FormProvider which is a Context.Provider (wraps layout component) with a state variable which stores function callback to submit a form. Now in the form component (which is loaded conditionally) I am using this setState func from context to assign form submit callback and in the toolbar using state variable from context to call that as a function. The problem I am facing is I always get state variable from context undefined. These are the snippets from my code.
FormProvider
type FormContextProps = {
setOnSubmit: (callable: Function | undefined) => void
assignOnSubmit: Dispatch<any>
setOnCancel: (callable: Function | undefined) => void
submit: (e: any) => void
cancel: () => void
}
const initAuthContextPropsState = {
setOnSubmit: () => { },
assignOnSubmit: () => { },
setOnCancel: () => { },
submit: (e: any) => { },
cancel: () => { },
}
const FormContext = createContext<FormContextProps>(initAuthContextPropsState)
const useTForm = () => {
return useContext(FormContext)
}
const FormProvider: FC = ({ children }) => {
const [onSubmit, assignOnSubmit] = useState<Function | undefined>()
const [onCancel, assignOnCancel] = useState<Function | undefined>()
const setOnSubmit = (callable: Function | undefined) => {
console.log('setOnSubmit', callable)
assignOnSubmit(callable)
console.log('setOnSubmit after', onSubmit)
}
const setOnCancel = (callable: Function | undefined) => {
assignOnCancel(callable)
}
useEffect(() => {
console.log("changed onSubmit"); // this hook is called only on first render
}, [onSubmit])
const submit = (e: any) => {
console.log('form submited', onSubmit) // this is always undefined when I click on save button on toolbar
if (onSubmit) onSubmit(e)
}
const cancel = () => {
if (onCancel) onCancel()
}
return (
<FormContext.Provider value={{ setOnSubmit, assignOnSubmit, setOnCancel, submit, cancel }}>
{children}
</FormContext.Provider>
)
}
Toolbar
const FormToolbar: FC = () => {
const {classes} = useLayout()
const {submit, cancel} = useTForm()
const submitForm = (e: any) => submit(e)
return (
<div className='toolbar' id='kt_toolbar'>
{/* begin::Container */}
<div
id='kt_toolbar_container'
className={clsx(classes.toolbarContainer.join(' '), 'd-flex flex-stack')}
>
<DefaultTitle />
{/* begin::Actions */}
<div className='py-1 d-flex align-items-center'>
{/* begin::Button */}
<button
className='btn btn-sm btn-primary me-4'
onClick={submitForm}
>
Save
</button>
<button
className='btn btn-sm btn-primary'
onClick={cancel}
>
Cancel
</button>
{/* end::Button */}
</div>
{/* end::Actions */}
</div>
{/* end::Container */}
</div>
)
}
EditForm.tsx
const EditForm: React.FC<Props> = () = {
const form = useRef() as React.MutableRefObject<HTMLFormElement>
const { setOnSubmit, assignOnSubmit } = useTForm()
useLayoutEffect(() => {
setOnSubmit(() => { form?.current.dispatchEvent(new Event('submit')) });
console.log('Form changed', form)
}, [form])
return (
<form onSubmit={formik.handleSubmit} ref={form}>
// ...
</form>
);
}
Main Component
function StaffManagement({ user, selectedLanguageId, idMenu }: Props) {
const [editing, setEditing]: [any, Function] = useState(null)
return (
<div className='row'>
<div className="col-lg-4">
<ModuleItemList
className='card-xxl-stretch mb-xl-3'
edit={setEditing}
/>
</div>
<div className="col-lg-8">
{editing && <EditForm
userId={user.id}
menuId={idMenu}
/>}
</div>
</div>
)
}
When using setState, we can do it in two ways,
setState(newState); // directly pass the new state
setState((currentState) => newState); // return the new state from a callback fn
That mean setState can accept a plain state value or a callback function which will return the new state that need to be set as the new state.
When you say,
const setOnSubmit = (callable: Function | undefined) => {
// callable => () => { form?.current.dispatchEvent(new Event('submit')) }
assignOnSubmit(callable)
}
Here React thinks you used the setState(assignOnSubmit) in the 2nd way I mentioned above, so react will call your callback and execute the form?.current.dispatchEvent(new Event('submit')). Since your callable function returns nothing, undefined will assigned to your onSubmit state.
So if you really need to store this function in a state, you have to do it as,
const setOnSubmit = (callable: Function | undefined) => {
assignOnSubmit(() => callable) // React will call the callback and return callable
}
Few Other Tips
Also do not use useLayoutEffect for this task. You can use useEffect and imrpove the performance of your application.
memoize the provider data, otherwise you will trigger unwanted re renders.
const data = useMemo(() => ({
setOnSubmit, assignOnSubmit, setOnCancel, submit, cancel
}), [submit, cancel, setOnCancel, assignOnSubmit, setOnSubmit])
return (
<FormContext.Provider value={data}>
{children}
</FormContext.Provider>
)
State updates are asynchronous. So you can't expect to console.log log the latest state
const setOnSubmit = (callable: Function | undefined) => {
console.log('setOnSubmit', callable)
assignOnSubmit(() => callable)
console.log('setOnSubmit after', onSubmit) // this won't log the latest as assignOnSubmit is async
}
you need to make <FormProvider as a parent of your Toolbar and EditForm to make your context working properly. Based on your code I don't see where you put the <FormProvider, so I'm guessing that you need to put it on your Main Component
Main Component
function StaffManagement({ user, selectedLanguageId, idMenu }: Props) {
const [editing, setEditing]: [any, Function] = useState(null)
return (
<FormProvider>
<div className='row'>
<div className="col-lg-4">
<ModuleItemList
className='card-xxl-stretch mb-xl-3'
edit={setEditing}
/>
</div>
<div className="col-lg-8">
{editing && <EditForm
userId={user.id}
menuId={idMenu}
/>}
</div>
</div>
</FormProvider>
)
I am trying to apply a change to only one item in an array depending on a prop.
I have this list:
interface FieldProps {
fileLimitWarning?: // I STILL NEED TO FIGURE THIS OUT
}
const DataField = (props: FieldProps) => {
const { fileLimitWarning, handleFileSelection } = props;
return (
<>
{fileLimitWarning && <p>This file exceeds the max size of 250mb</p>}
<input onChange={e => handleFileSelection(e.target.files)} />
</>
}
const ContainerOfDataField = () => {
const [fileLimitWarning, setFileLimitWarning] = useState(false);
const handleFileSelection = (files) => {
setFileLimitWarning(false);
const [currentFile] = files;
if(currentFile?.size <= 250000000) {
setFileLimitWarning(true);
}
}
return (
<ul>
{
fields?.map((promoField: Field, index: number) => {
return (
<DataField
key={index}
fileLimitWarning={fileLimitWarning}
handleFileSelection={handleFileSelection}
/>
);
})
}
</ul>
)
}
In this case what I want is to only return null in the DataField component when it corresponds. Right now whenever that fileLimitWarning === true on the ContainerOfDataField component, it hides/removes/deletes all of the Typography nodes from the DataField component. So what I need is to hide only the index that matches where the problem is coming from.
Is it clear?
I think ideally you would define fileLimitWarning in each iteration of your map, since (I assume) it is a property of the current item, rather than a global property:
return (
<ul>
{
fields?.map((promoField: Field, index: number) => {
// { currentFile } = promoField???
return (
<DataField
key={index}
fileLimitWarning={currentFile?.size <= 250000000}
handleFileSelection={handleFileSelection}
/>
);
})
}
</ul>
)
}
Just wondering the best way to pass the letterSelected into the useLazyQuery fetchMovies query, so that I don't have to use the static variable of "A". I was hoping there was a way to pass it directly into fetchMovies. useLazyQuery is an apollo query.
const BrowseMovies = () => {
const [fetchMovies, { data, loading}] = useLazyQuery(BROWSE_MOVIES_BY_LETTER, {
variables: {
firstLetter: "A"
}
})
return (
<div className="browserWrapper">
<h2>Browse Movies</h2>
<AlphabetSelect
pushLetterToParent={fetchMovies}
/>
{
data && !loading &&
data.browseMovies.map((movie: any) => {
return (
<div className="browseRow">
<a className="movieTitle">
{movie.name}
</a>
</div>
)
})
}
</div>
)
}
export default BrowseMovies
const AlphabetSelect = ({pushLetterToParent}: any) => {
const letters = ['A','B','C','D','E','F','G','H','I','J','K','L', 'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','#']
const [selectedLetter, setSelectedLetter] = useState("A")
const onLetterSelect = (letter: string) => {
setSelectedLetter(letter.toUpperCase())
pushLetterToParent(letter.toUpperCase())
}
return (
<div className="alphabetSelect">
{
letters.map((letter: string) => {
return(
<div
className={selectedLetter === letter ? 'letterSelectActive' : 'letterSelect'}
onClick={() => onLetterSelect(letter)}
>
{letter}
</div>
)
})
}
</div>
)
}
export default AlphabetSelect
This appears to be a problem solved by Lifting State Up. useLazyQuery takes a gql query and options and returns a function to execute the query at a later time. Sounds like you want the child component to update the variables config parameter.
BrowseMovies
Move firstLetter state BrowseMovies component
Update query parameters/options/config from state
Add useEffect to trigger fetch when state updates
Pass firstLetter state and setFirstLetter state updater to child component
const BrowseMovies = () => {
const [firstLetter, setFirstLetter] = useState('');
const [fetchMovies, { data, loading}] = useLazyQuery(
BROWSE_MOVIES_BY_LETTER,
{ variables: { firstLetter } } // <-- pass firstLetter state
);
useEffect(() => {
if (firstLetter) {
fetchMovies(); // <-- invoke fetch on state update
}
}, [firstLetter]);
return (
<div className="browserWrapper">
<h2>Browse Movies</h2>
<AlphabetSelect
pushLetterToParent={setFirstLetter} // <-- pass state updater
selectedLetter={firstLetter} // <-- pass state
/>
{
data && !loading &&
data.browseMovies.map((movie: any, index: number) => {
return (
<div key={index} className="browseRow">
<a className="movieTitle">
{movie.name}
</a>
</div>
)
})
}
</div>
)
}
AlphabetSelect
Attach pushLetterToParent callback to div's onClick handler
const AlphabetSelect = ({ pushLetterToParent, selectedLetter }: any) => {
const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ#';
return (
<div className="alphabetSelect">
{
letters.split('').map((letter: string) => {
return(
<div
key={letter}
className={selectedLetter === letter ? 'letterSelectActive' : 'letterSelect'}
onClick={() => pushLetterToParent(letter.toUpperCase())}
>
{letter}
</div>
)
})
}
</div>
)
}
I have a parent and a child component, child component has a button, which I'd like to disable it after the first click. This answer works for me in child component. However the function executed on click now exists in parent component, how could I pass the attribute down to the child component? I tried the following and it didn't work.
Parent:
const Home = () => {
let btnRef = useRef();
const handleBtnClick = () => {
if (btnRef.current) {
btnRef.current.setAttribute("disabled", "disabled");
}
}
return (
<>
<Card btnRef={btnRef} handleBtnClick={handleBtnClick} />
</>
)
}
Child:
const Card = ({btnRef, handleBtnClick}) => {
return (
<div>
<button ref={btnRef} onClick={handleBtnClick}>Click me</button>
</div>
)
}
In general, refs should be used only as a last resort in React. React is declarative by nature, so instead of the parent "making" the child disabled (which is what you are doing with the ref) it should just "say" that the child should be disabled (example below):
const Home = () => {
const [isButtonDisabled, setIsButtonDisabled] = useState(false)
const handleButtonClick = () => {
setIsButtonDisabled(true)
}
return (
<>
<Card isDisabled={isButtonDisabled} onButtonClick={handleButtonClick} />
</>
)
}
const Card = ({isDisabled, onButtonClick}) => {
return (
<div>
<button disabled={isDisabled} onClick={onButtonClick}>Click me</button>
</div>
)
}
Actually it works if you fix the typo in prop of Card component. Just rename hadnlBtnClick to handleBtnClick
You don't need to mention each prop/attribute by name as you can use javascript Object Destructuring here.
const Home = () => {
const [isButtonDisabled, setIsButtonDisabled] = useState(false)
const handleButtonClick = () => {
setIsButtonDisabled(true)
}
return (
<>
<Card isDisabled={isButtonDisabled} onButtonClick={handleButtonClick} />
</>
)
}
const Card = (props) => {
return (
<div>
<button {...props}>Click me</button>
</div>
)
}
You can also select a few props and use them differently in the child components. for example, see the text prop below.
const Home = () => {
const [isButtonDisabled, setIsButtonDisabled] = useState(false)
const handleButtonClick = () => {
setIsButtonDisabled(true)
}
return (
<>
<Card text="I'm a Card" isDisabled={isButtonDisabled} onButtonClick={handleButtonClick} />
</>
)
}
const Card = ({text, ...restProps}) => {
return (
<div>
<button {...restProps}>{text}</button>
</div>
)
}
What am I looking for?
A way to use setState() on an input element that updates my state immediately with onChange.
What have I done so far?
I have two components, BooksApp and SearchBook. I am passing result to SearchBook as a prop to be rendered. Then I am capturing the changes on the input element using onChange. The onChange is calling the method I passed as a prop as well.
React documentation says the following, but if I use a callback and then in the callback I invoke setState() it sounds to me that I am back at the same situation, because setState() will again be async:
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.
What is the issue?
If the user erases the content of the input too quickly, although there is still a console.log('empty') in the console, the setState() does not run and thus result stays the same and does not become an empty array.
This is the content of App.js:
class BooksApp extends Component {
state = {
books: [],
result: [],
query: ''
}
updateQuery = (query) => {
this.setState({ query: query.trim() })
}
objDigger = (arr, diggers) => {
const digged = [];
diggers.forEach((d) => {
let o = {};
o = arr.filter((a) => a.id === d);
o.forEach((i) => {
digged.push(i);
})
});
return digged;
}
filterHelper = (result) => {
const resultKeys = result.map((r) => r.id)
const stateKeys = this.state.books.map((s) => s.id)
// this.objDigger(this.state.books, stateKeys)
// new books
const newKeys = _array.difference(resultKeys, stateKeys);
const newObjs = this.objDigger(result, newKeys)
// existing books
const existingKeys = _array.difference(resultKeys, newKeys)
const existingObjs = this.objDigger(this.state.books, existingKeys);
// search books
const searchObjs = newObjs.concat(existingObjs);
return searchObjs;
}
searchBook = (query) => {
this.updateQuery(query);
if (query) {
BooksAPI.search(query).then((result) => {
result = this.filterHelper(result)
if (!result.error) {
this.setState({
result,
})
}
})
} else {
console.log('empty');
this.setState(state => ({
result: []
}));
}
}
appHandleChange = (query) => {
console.log('searching');
this.searchBook(query);
}
render() {
return (
<div className="app">
<Route path="/search" render={() => (
<SearchBook
result={ this.state.result }
onChange={ this.appHandleChange }
onChangeShelf={ this.changeShelf }/>
)}>
</Route>
</div>
)
}
}
This is the content of SearchBook:
class SearchBook extends Component {
handleChange = (book, newShelf) => {
this.props.onChangeShelf(book, newShelf);
}
handleInputChange = (event) => {
this.props.onChange(event.target.value);
}
render() {
const { result } = this.props;
return (
<div className="search-books">
<div className="search-books-bar">
<Link
to="/"
className="close-search"
>
Close
</Link>
<div className="search-books-input-wrapper">
<input
type="text"
placeholder="Search by title or author"
onChange={ (event) => this.handleInputChange(event) }
/>
</div>
</div>
<div className="search-books-results">
<ol className="books-grid">
{result.length>0 && result.map((book) => (
<li key={book.id}>
<div className="book">
<div className="book-top">
<div className="book-cover" style={{ width: 128, height: 193, backgroundImage: `url(${book.imageLinks && book.imageLinks.smallThumbnail})` }}></div>
<BookShelfChanger
shelf={book.shelf ? book.shelf : 'none'}
onChangeShelf={(newShelf) => {
this.handleChange(book, newShelf)
}}
></BookShelfChanger>
</div>
<div className="book-title">{book.title}</div>
<div className="book-authors">{book.authors}</div>
</div>
</li>
))}
</ol>
</div>
</div>
)
}
}