How should I get a value from child component to parent component: via refs or via callbacks?

  javascript, react-native, reactjs

I have read few posts on the topic, but still it is not clear to me what is the right approach. I have a child component, called TextBox.js and a parent component called CommentsList.js which shows all the comments. Once I type the text in TextBox.js, I press a button (part of CommentsList.js) and I do something with this text. Here is my CommntsList.js component:

import TextBox from "./TextBox";



const CommentsList = (props) => {

  return (
    <View style={styles.container}>
      <View style={styles.view}>
        <TextBox title="Write a comment..." />
        <TouchableOpacity
          onPress={() => console.log("my comment is: ", )}
        >
          <Text>Post</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};  

export default CommentsList;

My TextBox.js component – essentially a text box, which allows for people to be tagged in.

import MentionsTextInput from "react-native-mentions";

import firebase from "firebase";
require("firebase/firestore");
require("firebase/firebase-storage");

const TextBox = ({ title }) => {
  const [text, setText] = useState("");
  const [data, setData] = useState("");
  const [keyword, setKeyword] = useState("");

  const renderSuggestionsRow = ({ item }, hidePanel) => {
    return (
      // RENDER USERS SUGGESTIONS; ALSO NOT RELATED TO MY QUESTION
    );
  };

  const onSuggestionTap = (name, hidePanel) => {
    hidePanel();
    const comment = text.slice(0, -keyword.length);
    setText(comment + "@" + name + " ");
    setData("");
  };

  const callback = (keyword) => {
    if (keyword.length >= 2) {
      setKeyword(keyword);
          //GET TAGGED USERS; NOT RELATED TO MY QUESTION
          setData(result);
        });
    }
  };

  return (
    <View
      style={[{ margin: 5, borderColor: "green", borderWidth: 2, flex: 1 }]}
    >
      <MentionsTextInput
        textInputStyle={styles.textInputStyle}
        suggestionsPanelStyle={{ backgroundColor: "rgba(100,100,100,0.1)" }}
        loadingComponent={() => (
          <View style={styles.viewStyle}>
            <ActivityIndicator />
          </View>
        )}
        textInputMinHeight={30}
        textInputMaxHeight={80}
        trigger={"@"}
        triggerLocation={"anywhere"} // 'new-word-only', 'anywhere'
        value={text}
        onChangeText={(val) => setText(val)}
        triggerCallback={callback.bind(this)}
        renderSuggestionsRow={renderSuggestionsRow.bind(this)}
        suggestionsData={data}
        keyExtractor={(item, index) => item.id}
        suggestionRowHeight={45}
        horizontal={true}
        MaxVisibleRowCount={3}
        placeholder={title}
      />
    </View>
  );
};

export default TextBox;

My question is: how do I get the text value from the child component into my parent component?

Source: Ask Javascript Questions

LEAVE A COMMENT