Search code examples
javascriptreactjsdomdom-eventsreact-dom

How to call a variable from a react function in a file to another function in a different file


On building a podcast with reactjs framework I got hooked up some where. Since on building the page header I made each header part to be a component. Below are some snippets for that:

Searchform.js

import React, {useState} from 'react';
import './searchForm.css';
import Data from '../../../tracks/tracks.json'

export default function SearchForm() {
    const [query, setQuery] = useState("");
    return ([(<div>
            <form className="no_submit mx-5">
                <input onChange={(event) =>
                    setQuery(event.target.value)}
                       className="no_submit col-xs-4 px-5 input-sm"
                       type="search"
                       placeholder="Search podcasts..."
                />
            </form>
            {Data.filter((pod) => {
                if (query === "") {
                    return pod;
                } else if (
                    pod.title.toLowerCase().includes(
                        query.toLowerCase()
                    )
                ) {
                    return pod;
                }
                return null;
            }).map(
                (pod, index) =>
                    (
                        <div key={index}>
                            <p>{pod.title}</p>
                            <p>{pod.fileUrl}</p>
                        </div>
                    )
            )}
        </div>)]
    );
}

playlist.js

import './searchForm.css';
import Data from '../../../tracks/tracks.json'

export default function SearchForm() {
    const [query, setQuery] = useState("");
    return ([(<div> ...

Question:

How can I get the value of the input field from the searchform.js into the playlist.js

No working:

Declaring the variable out of the class before calling it renders an error message.


Solution

  • Finally, I got knowledge of React useContext. Alternatively redux is another alternative for this task. I have finish with this.

    Thanks!